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.
12 use std::cell::{Cell, RefCell};
13 use std::collections::BTreeSet;
14 use std::collections::HashMap;
20 use std::path::{Path, PathBuf};
21 use std::process::Command;
22 use std::time::{Duration, Instant};
24 use cache::{Cache, Interned, INTERNER};
29 use flags::Subcommand;
34 use util::{add_lib_path, exe, libdir};
35 use {Build, DocTests, Mode};
39 use petgraph::graph::NodeIndex;
42 pub struct Builder<'a> {
47 stack: RefCell<Vec<Box<Any>>>,
48 time_spent_on_dependencies: Cell<Duration>,
49 pub paths: Vec<PathBuf>,
50 graph_nodes: RefCell<HashMap<String, NodeIndex>>,
51 graph: RefCell<Graph<String, bool>>,
52 parent: Cell<Option<NodeIndex>>,
55 impl<'a> Deref for Builder<'a> {
58 fn deref(&self) -> &Self::Target {
63 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
64 /// `PathBuf` when directories are created or to return a `Compiler` once
65 /// it's been assembled.
68 const DEFAULT: bool = false;
70 /// Run this rule for all hosts without cross compiling.
71 const ONLY_HOSTS: bool = false;
73 /// Primary function to execute this rule. Can call `builder.ensure(...)`
74 /// with other steps to run those.
75 fn run(self, builder: &Builder) -> Self::Output;
77 /// When bootstrap is passed a set of paths, this controls whether this rule
78 /// will execute. However, it does not get called in a "default" context
79 /// when we are not passed any paths; in that case, make_run is called
81 fn should_run(run: ShouldRun) -> ShouldRun;
83 /// Build up a "root" rule, either as a default rule or from a path passed
86 /// When path is `None`, we are executing in a context where no paths were
87 /// passed. When `./x.py build` is run, for example, this rule could get
88 /// called if it is in the correct list below with a path of `None`.
89 fn make_run(_run: RunConfig) {
90 // It is reasonable to not have an implementation of make_run for rules
91 // who do not want to get called from the root context. This means that
92 // they are likely dependencies (e.g., sysroot creation) or similar, and
93 // as such calling them from ./x.py isn't logical.
98 pub struct RunConfig<'a> {
99 pub builder: &'a Builder<'a>,
100 pub host: Interned<String>,
101 pub target: Interned<String>,
105 struct StepDescription {
108 should_run: fn(ShouldRun) -> ShouldRun,
109 make_run: fn(RunConfig),
113 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
115 Set(BTreeSet<PathBuf>),
120 fn empty() -> PathSet {
121 PathSet::Set(BTreeSet::new())
124 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
125 let mut set = BTreeSet::new();
126 set.insert(path.into());
130 fn has(&self, needle: &Path) -> bool {
132 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
133 PathSet::Suite(_) => false,
137 fn path(&self, builder: &Builder) -> PathBuf {
139 PathSet::Set(set) => set
142 .unwrap_or(&builder.build.src)
144 PathSet::Suite(path) => PathBuf::from(path),
149 impl StepDescription {
150 fn from<S: Step>() -> StepDescription {
153 only_hosts: S::ONLY_HOSTS,
154 should_run: S::should_run,
155 make_run: S::make_run,
156 name: unsafe { ::std::intrinsics::type_name::<S>() },
160 fn maybe_run(&self, builder: &Builder, pathset: &PathSet) {
161 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
162 eprintln!("Skipping {:?} because it is excluded", pathset);
164 } else if !builder.config.exclude.is_empty() {
166 "{:?} not skipped for {:?} -- not in {:?}",
167 pathset, self.name, builder.config.exclude
170 let hosts = &builder.hosts;
172 // Determine the targets participating in this rule.
173 let targets = if self.only_hosts {
174 if !builder.config.run_host_only {
175 return; // don't run anything
184 for target in targets {
185 let run = RunConfig {
187 path: pathset.path(builder),
191 (self.make_run)(run);
196 fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
199 .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
200 .collect::<Vec<_>>();
202 // sanity checks on rules
203 for (desc, should_run) in v.iter().zip(&should_runs) {
205 !should_run.paths.is_empty(),
206 "{:?} should have at least one pathset",
211 if paths.is_empty() {
212 for (desc, should_run) in v.iter().zip(should_runs) {
213 if desc.default && should_run.is_really_default {
214 for pathset in &should_run.paths {
215 desc.maybe_run(builder, pathset);
221 let mut attempted_run = false;
222 for (desc, should_run) in v.iter().zip(&should_runs) {
223 if let Some(suite) = should_run.is_suite_path(path) {
224 attempted_run = true;
225 desc.maybe_run(builder, suite);
226 } else if let Some(pathset) = should_run.pathset_for_path(path) {
227 attempted_run = true;
228 desc.maybe_run(builder, pathset);
233 panic!("Error: no rules matched {}.", path.display());
241 pub struct ShouldRun<'a> {
242 pub builder: &'a Builder<'a>,
243 // use a BTreeSet to maintain sort order
244 paths: BTreeSet<PathSet>,
246 // If this is a default rule, this is an additional constraint placed on
247 // its run. Generally something like compiler docs being enabled.
248 is_really_default: bool,
251 impl<'a> ShouldRun<'a> {
252 fn new(builder: &'a Builder) -> ShouldRun<'a> {
255 paths: BTreeSet::new(),
256 is_really_default: true, // by default no additional conditions
260 pub fn default_condition(mut self, cond: bool) -> Self {
261 self.is_really_default = cond;
265 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
266 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
267 // actually doing something different for every crate passed.
268 pub fn all_krates(mut self, name: &str) -> Self {
269 let mut set = BTreeSet::new();
270 for krate in self.builder.in_tree_crates(name) {
271 set.insert(PathBuf::from(&krate.path));
273 self.paths.insert(PathSet::Set(set));
277 pub fn krate(mut self, name: &str) -> Self {
278 for krate in self.builder.in_tree_crates(name) {
279 self.paths.insert(PathSet::one(&krate.path));
284 // single, non-aliased path
285 pub fn path(self, path: &str) -> Self {
289 // multiple aliases for the same job
290 pub fn paths(mut self, paths: &[&str]) -> Self {
292 .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
296 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
297 self.paths.iter().find(|pathset| match pathset {
298 PathSet::Suite(p) => path.starts_with(p),
299 PathSet::Set(_) => false,
303 pub fn suite_path(mut self, suite: &str) -> Self {
304 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
308 // allows being more explicit about why should_run in Step returns the value passed to it
309 pub fn never(mut self) -> ShouldRun<'a> {
310 self.paths.insert(PathSet::empty());
314 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
315 self.paths.iter().find(|pathset| pathset.has(path))
319 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
330 impl<'a> Builder<'a> {
331 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
332 macro_rules! describe {
333 ($($rule:ty),+ $(,)*) => {{
334 vec![$(StepDescription::from::<$rule>()),+]
338 Kind::Build => describe!(
342 compile::StartupObjects,
346 tool::UnstableBookGen,
351 tool::RemoteTestServer,
352 tool::RemoteTestClient,
363 Kind::Check => describe!(
367 check::CodegenBackend,
370 Kind::Test => describe!(
378 test::RunPassValgrind,
385 test::RunPassFullDeps,
386 test::RunFailFullDeps,
387 test::CompileFailFullDeps,
388 test::IncrementalFullDeps,
393 test::RunPassValgrindPretty,
394 test::RunPassFullDepsPretty,
395 test::RunFailFullDepsPretty,
405 test::RunMakeFullDeps,
418 // Run run-make last, since these won't pass without make on Windows
422 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
423 Kind::Doc => describe!(
425 doc::UnstableBookGen,
430 doc::WhitelistedRustc,
441 Kind::Dist => describe!(
446 dist::DebuggerScripts,
450 dist::PlainSourceTarball,
457 Kind::Install => describe!(
470 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
471 let kind = match subcommand {
472 "build" => Kind::Build,
474 "test" => Kind::Test,
475 "bench" => Kind::Bench,
476 "dist" => Kind::Dist,
477 "install" => Kind::Install,
481 let builder = Builder {
483 top_stage: build.config.stage.unwrap_or(2),
486 stack: RefCell::new(Vec::new()),
487 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
489 graph_nodes: RefCell::new(HashMap::new()),
490 graph: RefCell::new(Graph::new()),
491 parent: Cell::new(None),
494 let builder = &builder;
495 let mut should_run = ShouldRun::new(builder);
496 for desc in Builder::get_step_descriptions(builder.kind) {
497 should_run = (desc.should_run)(should_run);
499 let mut help = String::from("Available paths:\n");
500 for pathset in should_run.paths {
501 if let PathSet::Set(set) = pathset {
502 set.iter().for_each(|path| {
504 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
512 pub fn new(build: &Build) -> Builder {
513 let (kind, paths) = match build.config.cmd {
514 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
515 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
516 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
517 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
518 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
519 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
520 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
521 Subcommand::Clean { .. } => panic!(),
524 let builder = Builder {
526 top_stage: build.config.stage.unwrap_or(2),
529 stack: RefCell::new(Vec::new()),
530 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
531 paths: paths.to_owned(),
532 graph_nodes: RefCell::new(HashMap::new()),
533 graph: RefCell::new(Graph::new()),
534 parent: Cell::new(None),
537 if kind == Kind::Dist {
539 !builder.config.test_miri,
540 "Do not distribute with miri enabled.\n\
541 The distributed libraries would include all MIR (increasing binary size).
542 The distributed MIR would include validation statements."
549 pub fn execute_cli(&self) -> Graph<String, bool> {
550 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
551 self.graph.borrow().clone()
554 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
555 let paths = paths.unwrap_or(&[]);
556 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
559 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
560 StepDescription::run(v, self, paths);
563 /// Obtain a compiler at a given stage and for a given host. Explicitly does
564 /// not take `Compiler` since all `Compiler` instances are meant to be
565 /// obtained through this function, since it ensures that they are valid
566 /// (i.e., built and assembled).
567 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
568 self.ensure(compile::Assemble {
569 target_compiler: Compiler { stage, host },
573 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
574 self.ensure(compile::Sysroot { compiler })
577 /// Returns the libdir where the standard library and other artifacts are
578 /// found for a compiler's sysroot.
579 pub fn sysroot_libdir(
582 target: Interned<String>,
583 ) -> Interned<PathBuf> {
584 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
587 target: Interned<String>,
589 impl Step for Libdir {
590 type Output = Interned<PathBuf>;
592 fn should_run(run: ShouldRun) -> ShouldRun {
596 fn run(self, builder: &Builder) -> Interned<PathBuf> {
597 let compiler = self.compiler;
598 let config = &builder.build.config;
599 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
600 builder.build.config.libdir_relative().unwrap()
604 let sysroot = builder
605 .sysroot(self.compiler)
610 let _ = fs::remove_dir_all(&sysroot);
611 t!(fs::create_dir_all(&sysroot));
612 INTERNER.intern_path(sysroot)
615 self.ensure(Libdir { compiler, target })
618 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
619 self.sysroot_libdir(compiler, compiler.host)
620 .with_file_name(self.config.rust_codegen_backends_dir.clone())
623 /// Returns the compiler's libdir where it stores the dynamic libraries that
624 /// it itself links against.
626 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
628 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
629 if compiler.is_snapshot(self) {
630 self.rustc_snapshot_libdir()
632 self.sysroot(compiler).join(libdir(&compiler.host))
636 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
637 /// library lookup path.
638 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
639 // Windows doesn't need dylib path munging because the dlls for the
640 // compiler live next to the compiler and the system will find them
646 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
649 /// Get a path to the compiler specified.
650 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
651 if compiler.is_snapshot(self) {
652 self.initial_rustc.clone()
654 self.sysroot(compiler)
656 .join(exe("rustc", &compiler.host))
660 pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
661 self.ensure(tool::Rustdoc { host })
664 pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
665 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
666 let compiler = self.compiler(self.top_stage, host);
667 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
668 .env("RUSTC_SYSROOT", self.sysroot(compiler))
671 self.sysroot_libdir(compiler, self.config.build),
673 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
674 .env("RUSTDOC_REAL", self.rustdoc(host))
675 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
676 .env("RUSTC_BOOTSTRAP", "1");
677 if let Some(linker) = self.linker(host) {
678 cmd.env("RUSTC_TARGET_LINKER", linker);
683 /// Prepares an invocation of `cargo` to be run.
685 /// This will create a `Command` that represents a pending execution of
686 /// Cargo. This cargo will be configured to use `compiler` as the actual
687 /// rustc compiler, its output will be scoped by `mode`'s output directory,
688 /// it will pass the `--target` flag for the specified `target`, and will be
689 /// executing the Cargo command `cmd`.
694 target: Interned<String>,
697 let mut cargo = Command::new(&self.initial_cargo);
698 let out_dir = self.stage_out(compiler, mode);
700 .env("CARGO_TARGET_DIR", out_dir)
705 // Set a flag for `check` so that certain build scripts can do less work
706 // (e.g. not building/requiring LLVM).
708 cargo.env("RUST_CHECK", "1");
711 cargo.arg("-j").arg(self.jobs().to_string());
712 // Remove make-related flags to ensure Cargo can correctly set things up
713 cargo.env_remove("MAKEFLAGS");
714 cargo.env_remove("MFLAGS");
716 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
717 // Force cargo to output binaries with disambiguating hashes in the name
718 let metadata = if compiler.stage == 0 {
719 // Treat stage0 like special channel, whether it's a normal prior-
720 // release rustc or a local rebuild with the same version, so we
721 // never mix these libraries by accident.
726 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
729 if compiler.stage == 0 && self.local_rebuild {
730 // Assume the local-rebuild rustc already has stage1 features.
733 stage = compiler.stage;
736 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
738 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
739 if !extra_args.is_empty() {
740 extra_args.push_str(" ");
742 extra_args.push_str(&s);
745 if !extra_args.is_empty() {
750 env::var("RUSTFLAGS").unwrap_or_default(),
756 let want_rustdoc = self.doc_tests != DocTests::No;
758 // Customize the compiler we're running. Specify the compiler to cargo
759 // as our shim and then pass it some various options used to configure
760 // how the actual compiler itself is called.
762 // These variables are primarily all read by
763 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
765 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
766 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
767 .env("RUSTC_REAL", self.rustc(compiler))
768 .env("RUSTC_STAGE", stage.to_string())
770 "RUSTC_DEBUG_ASSERTIONS",
771 self.config.rust_debug_assertions.to_string(),
773 .env("RUSTC_SYSROOT", self.sysroot(compiler))
774 .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
775 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
776 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
779 if cmd == "doc" || (cmd == "test" && want_rustdoc) {
780 self.rustdoc(compiler.host)
782 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
785 .env("TEST_MIRI", self.config.test_miri.to_string())
786 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
788 if let Some(host_linker) = self.linker(compiler.host) {
789 cargo.env("RUSTC_HOST_LINKER", host_linker);
791 if let Some(target_linker) = self.linker(target) {
792 cargo.env("RUSTC_TARGET_LINKER", target_linker);
794 if let Some(ref error_format) = self.config.rustc_error_format {
795 cargo.env("RUSTC_ERROR_FORMAT", error_format);
797 if cmd != "build" && cmd != "check" && want_rustdoc {
800 self.rustc_libdir(self.compiler(2, self.config.build)),
804 if mode == Mode::Tool {
805 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
806 // enabled in the config. Adding debuginfo makes them several times larger.
807 if self.config.rust_debuginfo_tools {
808 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
810 "RUSTC_DEBUGINFO_LINES",
811 self.config.rust_debuginfo_lines.to_string(),
815 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
817 "RUSTC_DEBUGINFO_LINES",
818 self.config.rust_debuginfo_lines.to_string(),
820 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
822 // Currently the compiler depends on crates from crates.io, and
823 // then other crates can depend on the compiler (e.g. proc-macro
824 // crates). Let's say, for example that rustc itself depends on the
825 // bitflags crate. If an external crate then depends on the
826 // bitflags crate as well, we need to make sure they don't
827 // conflict, even if they pick the same version of bitflags. We'll
828 // want to make sure that e.g. a plugin and rustc each get their
829 // own copy of bitflags.
831 // Cargo ensures that this works in general through the -C metadata
832 // flag. This flag will frob the symbols in the binary to make sure
833 // they're different, even though the source code is the exact
834 // same. To solve this problem for the compiler we extend Cargo's
835 // already-passed -C metadata flag with our own. Our rustc.rs
836 // wrapper around the actual rustc will detect -C metadata being
837 // passed and frob it with this extra string we're passing in.
838 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
841 if let Some(x) = self.crt_static(target) {
842 cargo.env("RUSTC_CRT_STATIC", x.to_string());
845 if let Some(x) = self.crt_static(compiler.host) {
846 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
849 // Enable usage of unstable features
850 cargo.env("RUSTC_BOOTSTRAP", "1");
851 self.add_rust_test_threads(&mut cargo);
853 // Almost all of the crates that we compile as part of the bootstrap may
854 // have a build script, including the standard library. To compile a
855 // build script, however, it itself needs a standard library! This
856 // introduces a bit of a pickle when we're compiling the standard
859 // To work around this we actually end up using the snapshot compiler
860 // (stage0) for compiling build scripts of the standard library itself.
861 // The stage0 compiler is guaranteed to have a libstd available for use.
863 // For other crates, however, we know that we've already got a standard
864 // library up and running, so we can use the normal compiler to compile
865 // build scripts in that situation.
867 // If LLVM support is disabled we need to use the snapshot compiler to compile
868 // build scripts, as the new compiler doesn't support executables.
869 if mode == Mode::Libstd || !self.config.llvm_enabled {
871 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
872 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
875 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
876 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
879 // Ignore incremental modes except for stage0, since we're
880 // not guaranteeing correctness across builds if the compiler
881 // is changing under your feet.`
882 if self.config.incremental && compiler.stage == 0 {
883 cargo.env("CARGO_INCREMENTAL", "1");
886 if let Some(ref on_fail) = self.config.on_fail {
887 cargo.env("RUSTC_ON_FAIL", on_fail);
890 if self.config.print_step_timings {
891 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
894 if self.config.backtrace_on_ice {
895 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
898 cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
900 // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
901 if self.config.deny_warnings && !(mode == Mode::Libstd && stage == 0) {
902 cargo.env("RUSTC_DENY_WARNINGS", "1");
905 // Throughout the build Cargo can execute a number of build scripts
906 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
907 // obtained previously to those build scripts.
908 // Build scripts use either the `cc` crate or `configure/make` so we pass
909 // the options through environment variables that are fetched and understood by both.
911 // FIXME: the guard against msvc shouldn't need to be here
912 if target.contains("msvc") {
913 if let Some(ref cl) = self.config.llvm_clang_cl {
914 cargo.env("CC", cl).env("CXX", cl);
917 let ccache = self.config.ccache.as_ref();
918 let ccacheify = |s: &Path| {
919 let ccache = match ccache {
921 None => return s.display().to_string(),
923 // FIXME: the cc-rs crate only recognizes the literal strings
924 // `ccache` and `sccache` when doing caching compilations, so we
925 // mirror that here. It should probably be fixed upstream to
926 // accept a new env var or otherwise work with custom ccache
929 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
930 _ => s.display().to_string(),
933 let cc = ccacheify(&self.cc(target));
934 cargo.env(format!("CC_{}", target), &cc).env("CC", &cc);
936 let cflags = self.cflags(target).join(" ");
938 .env(format!("CFLAGS_{}", target), cflags.clone())
939 .env("CFLAGS", cflags.clone());
941 if let Some(ar) = self.ar(target) {
942 let ranlib = format!("{} s", ar.display());
944 .env(format!("AR_{}", target), ar)
946 .env(format!("RANLIB_{}", target), ranlib.clone())
947 .env("RANLIB", ranlib);
950 if let Ok(cxx) = self.cxx(target) {
951 let cxx = ccacheify(&cxx);
953 .env(format!("CXX_{}", target), &cxx)
955 .env(format!("CXXFLAGS_{}", target), cflags.clone())
956 .env("CXXFLAGS", cflags);
961 && mode == Mode::Libstd
962 && self.config.extended
963 && compiler.is_final_stage(self)
965 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
968 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
969 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
971 // Environment variables *required* throughout the build
973 // FIXME: should update code to not require this env var
974 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
976 // Set this for all builds to make sure doc builds also get it.
977 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
979 // This one's a bit tricky. As of the time of this writing the compiler
980 // links to the `winapi` crate on crates.io. This crate provides raw
981 // bindings to Windows system functions, sort of like libc does for
982 // Unix. This crate also, however, provides "import libraries" for the
983 // MinGW targets. There's an import library per dll in the windows
984 // distribution which is what's linked to. These custom import libraries
985 // are used because the winapi crate can reference Windows functions not
986 // present in the MinGW import libraries.
988 // For example MinGW may ship libdbghelp.a, but it may not have
989 // references to all the functions in the dbghelp dll. Instead the
990 // custom import library for dbghelp in the winapi crates has all this
993 // Unfortunately for us though the import libraries are linked by
994 // default via `-ldylib=winapi_foo`. That is, they're linked with the
995 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
996 // conflict with the system MinGW ones). This consequently means that
997 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
998 // DLL) when linked against *again*, for example with procedural macros
999 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1000 // `-lwinapi_foo` to the linker again. This isn't actually available in
1001 // our distribution, however, so the link fails.
1003 // To solve this problem we tell winapi to not use its bundled import
1004 // libraries. This means that it will link to the system MinGW import
1005 // libraries by default, and the `-ldylib=foo` directives will still get
1006 // passed to the final linker, but they'll look like `-lfoo` which can
1007 // be resolved because MinGW has the import library. The downside is we
1008 // don't get newer functions from Windows, but we don't use any of them
1010 if mode != Mode::Tool {
1011 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1014 for _ in 1..self.verbosity {
1018 // This must be kept before the thinlto check, as we set codegen units
1019 // to 1 forcibly there.
1020 if let Some(n) = self.config.rust_codegen_units {
1021 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1024 if self.config.rust_optimize {
1025 // FIXME: cargo bench does not accept `--release`
1027 cargo.arg("--release");
1031 if self.config.locked_deps {
1032 cargo.arg("--locked");
1034 if self.config.vendor || self.is_sudo {
1035 cargo.arg("--frozen");
1038 self.ci_env.force_coloring_in_ci(&mut cargo);
1043 /// Ensure that a given step is built, returning its output. This will
1044 /// cache the step, so it is safe (and good!) to call this as often as
1045 /// needed to ensure that all dependencies are built.
1046 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1048 let mut stack = self.stack.borrow_mut();
1049 for stack_step in stack.iter() {
1052 .downcast_ref::<S>()
1053 .map_or(true, |stack_step| *stack_step != step)
1057 let mut out = String::new();
1058 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1059 for el in stack.iter().rev() {
1060 out += &format!("\t{:?}\n", el);
1064 if let Some(out) = self.cache.get(&step) {
1065 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1068 let mut graph = self.graph.borrow_mut();
1069 let parent = self.parent.get();
1073 .entry(format!("{:?}", step))
1074 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1075 if let Some(parent) = parent {
1076 graph.add_edge(parent, us, false);
1082 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1083 stack.push(Box::new(step.clone()));
1086 let prev_parent = self.parent.get();
1089 let mut graph = self.graph.borrow_mut();
1090 let parent = self.parent.get();
1094 .entry(format!("{:?}", step))
1095 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1096 self.parent.set(Some(us));
1097 if let Some(parent) = parent {
1098 graph.add_edge(parent, us, true);
1103 let start = Instant::now();
1104 let zero = Duration::new(0, 0);
1105 let parent = self.time_spent_on_dependencies.replace(zero);
1106 let out = step.clone().run(self);
1107 let dur = start.elapsed();
1108 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1112 self.parent.set(prev_parent);
1114 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1116 "[TIMING] {:?} -- {}.{:03}",
1119 dur.subsec_nanos() / 1_000_000
1124 let mut stack = self.stack.borrow_mut();
1125 let cur_step = stack.pop().expect("step stack empty");
1126 assert_eq!(cur_step.downcast_ref(), Some(&step));
1128 self.verbose(&format!(
1130 " ".repeat(self.stack.borrow().len()),
1133 self.cache.put(step, out.clone());
1144 fn configure(host: &[&str], target: &[&str]) -> Config {
1145 let mut config = Config::default_opts();
1146 // don't save toolstates
1147 config.save_toolstates = None;
1148 config.run_host_only = true;
1149 config.dry_run = true;
1150 // try to avoid spurious failures in dist where we create/delete each others file
1151 let dir = config.out.join("tmp-rustbuild-tests").join(
1154 .unwrap_or("unknown")
1157 t!(fs::create_dir_all(&dir));
1159 config.build = INTERNER.intern_str("A");
1160 config.hosts = vec![config.build]
1163 .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1164 .collect::<Vec<_>>();
1165 config.targets = config
1169 .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1170 .collect::<Vec<_>>();
1174 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1175 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1179 fn dist_baseline() {
1180 let build = Build::new(configure(&[], &[]));
1181 let mut builder = Builder::new(&build);
1182 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1184 let a = INTERNER.intern_str("A");
1187 first(builder.cache.all::<dist::Docs>()),
1188 &[dist::Docs { stage: 2, host: a },]
1191 first(builder.cache.all::<dist::Mingw>()),
1192 &[dist::Mingw { host: a },]
1195 first(builder.cache.all::<dist::Rustc>()),
1197 compiler: Compiler { host: a, stage: 2 }
1201 first(builder.cache.all::<dist::Std>()),
1203 compiler: Compiler { host: a, stage: 2 },
1207 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1211 fn dist_with_targets() {
1212 let build = Build::new(configure(&[], &["B"]));
1213 let mut builder = Builder::new(&build);
1214 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1216 let a = INTERNER.intern_str("A");
1217 let b = INTERNER.intern_str("B");
1220 first(builder.cache.all::<dist::Docs>()),
1222 dist::Docs { stage: 2, host: a },
1223 dist::Docs { stage: 2, host: b },
1227 first(builder.cache.all::<dist::Mingw>()),
1228 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1231 first(builder.cache.all::<dist::Rustc>()),
1233 compiler: Compiler { host: a, stage: 2 }
1237 first(builder.cache.all::<dist::Std>()),
1240 compiler: Compiler { host: a, stage: 2 },
1244 compiler: Compiler { host: a, stage: 2 },
1249 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1253 fn dist_with_hosts() {
1254 let build = Build::new(configure(&["B"], &[]));
1255 let mut builder = Builder::new(&build);
1256 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1258 let a = INTERNER.intern_str("A");
1259 let b = INTERNER.intern_str("B");
1262 first(builder.cache.all::<dist::Docs>()),
1264 dist::Docs { stage: 2, host: a },
1265 dist::Docs { stage: 2, host: b },
1269 first(builder.cache.all::<dist::Mingw>()),
1270 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1273 first(builder.cache.all::<dist::Rustc>()),
1276 compiler: Compiler { host: a, stage: 2 }
1279 compiler: Compiler { host: b, stage: 2 }
1284 first(builder.cache.all::<dist::Std>()),
1287 compiler: Compiler { host: a, stage: 2 },
1291 compiler: Compiler { host: a, stage: 2 },
1296 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1300 fn dist_with_targets_and_hosts() {
1301 let build = Build::new(configure(&["B"], &["C"]));
1302 let mut builder = Builder::new(&build);
1303 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1305 let a = INTERNER.intern_str("A");
1306 let b = INTERNER.intern_str("B");
1307 let c = INTERNER.intern_str("C");
1310 first(builder.cache.all::<dist::Docs>()),
1312 dist::Docs { stage: 2, host: a },
1313 dist::Docs { stage: 2, host: b },
1314 dist::Docs { stage: 2, host: c },
1318 first(builder.cache.all::<dist::Mingw>()),
1320 dist::Mingw { host: a },
1321 dist::Mingw { host: b },
1322 dist::Mingw { host: c },
1326 first(builder.cache.all::<dist::Rustc>()),
1329 compiler: Compiler { host: a, stage: 2 }
1332 compiler: Compiler { host: b, stage: 2 }
1337 first(builder.cache.all::<dist::Std>()),
1340 compiler: Compiler { host: a, stage: 2 },
1344 compiler: Compiler { host: a, stage: 2 },
1348 compiler: Compiler { host: a, stage: 2 },
1353 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1357 fn dist_with_target_flag() {
1358 let mut config = configure(&["B"], &["C"]);
1359 config.run_host_only = false; // as-if --target=C was passed
1360 let build = Build::new(config);
1361 let mut builder = Builder::new(&build);
1362 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1364 let a = INTERNER.intern_str("A");
1365 let b = INTERNER.intern_str("B");
1366 let c = INTERNER.intern_str("C");
1369 first(builder.cache.all::<dist::Docs>()),
1371 dist::Docs { stage: 2, host: a },
1372 dist::Docs { stage: 2, host: b },
1373 dist::Docs { stage: 2, host: c },
1377 first(builder.cache.all::<dist::Mingw>()),
1379 dist::Mingw { host: a },
1380 dist::Mingw { host: b },
1381 dist::Mingw { host: c },
1384 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1386 first(builder.cache.all::<dist::Std>()),
1389 compiler: Compiler { host: a, stage: 2 },
1393 compiler: Compiler { host: a, stage: 2 },
1397 compiler: Compiler { host: a, stage: 2 },
1402 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1406 fn dist_with_same_targets_and_hosts() {
1407 let build = Build::new(configure(&["B"], &["B"]));
1408 let mut builder = Builder::new(&build);
1409 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1411 let a = INTERNER.intern_str("A");
1412 let b = INTERNER.intern_str("B");
1415 first(builder.cache.all::<dist::Docs>()),
1417 dist::Docs { stage: 2, host: a },
1418 dist::Docs { stage: 2, host: b },
1422 first(builder.cache.all::<dist::Mingw>()),
1423 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1426 first(builder.cache.all::<dist::Rustc>()),
1429 compiler: Compiler { host: a, stage: 2 }
1432 compiler: Compiler { host: b, stage: 2 }
1437 first(builder.cache.all::<dist::Std>()),
1440 compiler: Compiler { host: a, stage: 2 },
1444 compiler: Compiler { host: a, stage: 2 },
1449 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1451 first(builder.cache.all::<compile::Std>()),
1454 compiler: Compiler { host: a, stage: 0 },
1458 compiler: Compiler { host: a, stage: 1 },
1462 compiler: Compiler { host: a, stage: 2 },
1466 compiler: Compiler { host: a, stage: 1 },
1470 compiler: Compiler { host: a, stage: 2 },
1476 first(builder.cache.all::<compile::Test>()),
1479 compiler: Compiler { host: a, stage: 0 },
1483 compiler: Compiler { host: a, stage: 1 },
1487 compiler: Compiler { host: a, stage: 2 },
1491 compiler: Compiler { host: a, stage: 1 },
1495 compiler: Compiler { host: a, stage: 2 },
1501 first(builder.cache.all::<compile::Assemble>()),
1504 target_compiler: Compiler { host: a, stage: 0 },
1507 target_compiler: Compiler { host: a, stage: 1 },
1510 target_compiler: Compiler { host: a, stage: 2 },
1513 target_compiler: Compiler { host: b, stage: 2 },
1520 fn build_default() {
1521 let build = Build::new(configure(&["B"], &["C"]));
1522 let mut builder = Builder::new(&build);
1523 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1525 let a = INTERNER.intern_str("A");
1526 let b = INTERNER.intern_str("B");
1527 let c = INTERNER.intern_str("C");
1529 assert!(!builder.cache.all::<compile::Std>().is_empty());
1530 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1532 first(builder.cache.all::<compile::Rustc>()),
1535 compiler: Compiler { host: a, stage: 0 },
1539 compiler: Compiler { host: a, stage: 1 },
1543 compiler: Compiler { host: a, stage: 2 },
1547 compiler: Compiler { host: b, stage: 2 },
1551 compiler: Compiler { host: a, stage: 0 },
1555 compiler: Compiler { host: a, stage: 1 },
1559 compiler: Compiler { host: a, stage: 2 },
1563 compiler: Compiler { host: b, stage: 2 },
1570 first(builder.cache.all::<compile::Test>()),
1573 compiler: Compiler { host: a, stage: 0 },
1577 compiler: Compiler { host: a, stage: 1 },
1581 compiler: Compiler { host: a, stage: 2 },
1585 compiler: Compiler { host: b, stage: 2 },
1589 compiler: Compiler { host: a, stage: 0 },
1593 compiler: Compiler { host: a, stage: 1 },
1597 compiler: Compiler { host: a, stage: 2 },
1601 compiler: Compiler { host: b, stage: 2 },
1605 compiler: Compiler { host: a, stage: 2 },
1609 compiler: Compiler { host: b, stage: 2 },
1617 fn build_with_target_flag() {
1618 let mut config = configure(&["B"], &["C"]);
1619 config.run_host_only = false;
1620 let build = Build::new(config);
1621 let mut builder = Builder::new(&build);
1622 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1624 let a = INTERNER.intern_str("A");
1625 let b = INTERNER.intern_str("B");
1626 let c = INTERNER.intern_str("C");
1628 assert!(!builder.cache.all::<compile::Std>().is_empty());
1630 first(builder.cache.all::<compile::Assemble>()),
1633 target_compiler: Compiler { host: a, stage: 0 },
1636 target_compiler: Compiler { host: a, stage: 1 },
1639 target_compiler: Compiler { host: b, stage: 1 },
1642 target_compiler: Compiler { host: a, stage: 2 },
1645 target_compiler: Compiler { host: b, stage: 2 },
1650 first(builder.cache.all::<compile::Rustc>()),
1653 compiler: Compiler { host: a, stage: 0 },
1657 compiler: Compiler { host: a, stage: 1 },
1661 compiler: Compiler { host: a, stage: 0 },
1665 compiler: Compiler { host: a, stage: 1 },
1672 first(builder.cache.all::<compile::Test>()),
1675 compiler: Compiler { host: a, stage: 0 },
1679 compiler: Compiler { host: a, stage: 1 },
1683 compiler: Compiler { host: a, stage: 2 },
1687 compiler: Compiler { host: b, stage: 2 },
1691 compiler: Compiler { host: a, stage: 0 },
1695 compiler: Compiler { host: a, stage: 1 },
1699 compiler: Compiler { host: a, stage: 2 },
1703 compiler: Compiler { host: b, stage: 2 },
1707 compiler: Compiler { host: a, stage: 2 },
1711 compiler: Compiler { host: b, stage: 2 },
1719 fn test_with_no_doc_stage0() {
1720 let mut config = configure(&[], &[]);
1721 config.stage = Some(0);
1722 config.cmd = Subcommand::Test {
1723 paths: vec!["src/libstd".into()],
1727 doc_tests: DocTests::No,
1732 let build = Build::new(config);
1733 let mut builder = Builder::new(&build);
1735 let host = INTERNER.intern_str("A");
1737 builder.run_step_descriptions(
1738 &[StepDescription::from::<test::Crate>()],
1739 &["src/libstd".into()],
1742 // Ensure we don't build any compiler artifacts.
1743 assert!(builder.cache.all::<compile::Rustc>().is_empty());
1745 first(builder.cache.all::<test::Crate>()),
1747 compiler: Compiler { host, stage: 0 },
1750 test_kind: test::TestKind::Test,
1751 krate: INTERNER.intern_str("std"),