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, GitRepo};
39 use petgraph::graph::NodeIndex;
42 pub struct Builder<'a> {
47 stack: RefCell<Vec<Box<dyn 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(suite) => suite.ends_with(needle),
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 // strip CurDir prefix if present
222 let path = match path.strip_prefix(".") {
227 let mut attempted_run = false;
228 for (desc, should_run) in v.iter().zip(&should_runs) {
229 if let Some(suite) = should_run.is_suite_path(path) {
230 attempted_run = true;
231 desc.maybe_run(builder, suite);
232 } else if let Some(pathset) = should_run.pathset_for_path(path) {
233 attempted_run = true;
234 desc.maybe_run(builder, pathset);
239 panic!("Error: no rules matched {}.", path.display());
247 pub struct ShouldRun<'a> {
248 pub builder: &'a Builder<'a>,
249 // use a BTreeSet to maintain sort order
250 paths: BTreeSet<PathSet>,
252 // If this is a default rule, this is an additional constraint placed on
253 // its run. Generally something like compiler docs being enabled.
254 is_really_default: bool,
257 impl<'a> ShouldRun<'a> {
258 fn new(builder: &'a Builder) -> ShouldRun<'a> {
261 paths: BTreeSet::new(),
262 is_really_default: true, // by default no additional conditions
266 pub fn default_condition(mut self, cond: bool) -> Self {
267 self.is_really_default = cond;
271 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
272 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
273 // actually doing something different for every crate passed.
274 pub fn all_krates(mut self, name: &str) -> Self {
275 let mut set = BTreeSet::new();
276 for krate in self.builder.in_tree_crates(name) {
277 set.insert(PathBuf::from(&krate.path));
279 self.paths.insert(PathSet::Set(set));
283 pub fn krate(mut self, name: &str) -> Self {
284 for krate in self.builder.in_tree_crates(name) {
285 self.paths.insert(PathSet::one(&krate.path));
290 // single, non-aliased path
291 pub fn path(self, path: &str) -> Self {
295 // multiple aliases for the same job
296 pub fn paths(mut self, paths: &[&str]) -> Self {
298 .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
302 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
303 self.paths.iter().find(|pathset| match pathset {
304 PathSet::Suite(p) => path.starts_with(p),
305 PathSet::Set(_) => false,
309 pub fn suite_path(mut self, suite: &str) -> Self {
310 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
314 // allows being more explicit about why should_run in Step returns the value passed to it
315 pub fn never(mut self) -> ShouldRun<'a> {
316 self.paths.insert(PathSet::empty());
320 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
321 self.paths.iter().find(|pathset| pathset.has(path))
325 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
336 impl<'a> Builder<'a> {
337 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
338 macro_rules! describe {
339 ($($rule:ty),+ $(,)*) => {{
340 vec![$(StepDescription::from::<$rule>()),+]
344 Kind::Build => describe!(
348 compile::CodegenBackend,
349 compile::StartupObjects,
353 tool::UnstableBookGen,
358 tool::RemoteTestServer,
359 tool::RemoteTestClient,
370 Kind::Check => describe!(
374 check::CodegenBackend,
377 Kind::Test => describe!(
383 test::RunPassValgrind,
390 test::RunPassFullDeps,
391 test::RunFailFullDeps,
392 test::CompileFailFullDeps,
397 test::RunPassValgrindPretty,
398 test::RunPassFullDepsPretty,
399 test::RunFailFullDepsPretty,
409 test::RunMakeFullDeps,
422 // Run bootstrap close to the end as it's unlikely to fail
424 // Run run-make last, since these won't pass without make on Windows
428 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
429 Kind::Doc => describe!(
431 doc::UnstableBookGen,
436 doc::WhitelistedRustc,
447 Kind::Dist => describe!(
452 dist::DebuggerScripts,
456 dist::PlainSourceTarball,
466 Kind::Install => describe!(
480 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
481 let kind = match subcommand {
482 "build" => Kind::Build,
484 "test" => Kind::Test,
485 "bench" => Kind::Bench,
486 "dist" => Kind::Dist,
487 "install" => Kind::Install,
491 let builder = Builder {
493 top_stage: build.config.stage.unwrap_or(2),
496 stack: RefCell::new(Vec::new()),
497 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
499 graph_nodes: RefCell::new(HashMap::new()),
500 graph: RefCell::new(Graph::new()),
501 parent: Cell::new(None),
504 let builder = &builder;
505 let mut should_run = ShouldRun::new(builder);
506 for desc in Builder::get_step_descriptions(builder.kind) {
507 should_run = (desc.should_run)(should_run);
509 let mut help = String::from("Available paths:\n");
510 for pathset in should_run.paths {
511 if let PathSet::Set(set) = pathset {
512 set.iter().for_each(|path| {
514 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
522 pub fn new(build: &Build) -> Builder {
523 let (kind, paths) = match build.config.cmd {
524 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
525 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
526 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
527 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
528 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
529 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
530 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
531 Subcommand::Clean { .. } => panic!(),
534 let builder = Builder {
536 top_stage: build.config.stage.unwrap_or(2),
539 stack: RefCell::new(Vec::new()),
540 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
541 paths: paths.to_owned(),
542 graph_nodes: RefCell::new(HashMap::new()),
543 graph: RefCell::new(Graph::new()),
544 parent: Cell::new(None),
547 if kind == Kind::Dist {
549 !builder.config.test_miri,
550 "Do not distribute with miri enabled.\n\
551 The distributed libraries would include all MIR (increasing binary size).
552 The distributed MIR would include validation statements."
559 pub fn execute_cli(&self) -> Graph<String, bool> {
560 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
561 self.graph.borrow().clone()
564 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
565 let paths = paths.unwrap_or(&[]);
566 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
569 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
570 StepDescription::run(v, self, paths);
573 /// Obtain a compiler at a given stage and for a given host. Explicitly does
574 /// not take `Compiler` since all `Compiler` instances are meant to be
575 /// obtained through this function, since it ensures that they are valid
576 /// (i.e., built and assembled).
577 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
578 self.ensure(compile::Assemble {
579 target_compiler: Compiler { stage, host },
583 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
584 self.ensure(compile::Sysroot { compiler })
587 /// Returns the libdir where the standard library and other artifacts are
588 /// found for a compiler's sysroot.
589 pub fn sysroot_libdir(
592 target: Interned<String>,
593 ) -> Interned<PathBuf> {
594 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
597 target: Interned<String>,
599 impl Step for Libdir {
600 type Output = Interned<PathBuf>;
602 fn should_run(run: ShouldRun) -> ShouldRun {
606 fn run(self, builder: &Builder) -> Interned<PathBuf> {
607 let compiler = self.compiler;
608 let config = &builder.build.config;
609 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
610 builder.build.config.libdir_relative().unwrap()
614 let sysroot = builder
615 .sysroot(self.compiler)
620 let _ = fs::remove_dir_all(&sysroot);
621 t!(fs::create_dir_all(&sysroot));
622 INTERNER.intern_path(sysroot)
625 self.ensure(Libdir { compiler, target })
628 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
629 self.sysroot_libdir(compiler, compiler.host)
630 .with_file_name(self.config.rust_codegen_backends_dir.clone())
633 /// Returns the compiler's libdir where it stores the dynamic libraries that
634 /// it itself links against.
636 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
638 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
639 if compiler.is_snapshot(self) {
640 self.rustc_snapshot_libdir()
642 self.sysroot(compiler).join(libdir(&compiler.host))
646 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
647 /// library lookup path.
648 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
649 // Windows doesn't need dylib path munging because the dlls for the
650 // compiler live next to the compiler and the system will find them
656 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
659 /// Get a path to the compiler specified.
660 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
661 if compiler.is_snapshot(self) {
662 self.initial_rustc.clone()
664 self.sysroot(compiler)
666 .join(exe("rustc", &compiler.host))
670 pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
671 self.ensure(tool::Rustdoc { host })
674 pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
675 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
676 let compiler = self.compiler(self.top_stage, host);
677 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
678 .env("RUSTC_SYSROOT", self.sysroot(compiler))
681 self.sysroot_libdir(compiler, self.config.build),
683 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
684 .env("RUSTDOC_REAL", self.rustdoc(host))
685 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
686 .env("RUSTC_BOOTSTRAP", "1");
687 if let Some(linker) = self.linker(host) {
688 cmd.env("RUSTC_TARGET_LINKER", linker);
693 /// Prepares an invocation of `cargo` to be run.
695 /// This will create a `Command` that represents a pending execution of
696 /// Cargo. This cargo will be configured to use `compiler` as the actual
697 /// rustc compiler, its output will be scoped by `mode`'s output directory,
698 /// it will pass the `--target` flag for the specified `target`, and will be
699 /// executing the Cargo command `cmd`.
704 target: Interned<String>,
707 let mut cargo = Command::new(&self.initial_cargo);
708 let out_dir = self.stage_out(compiler, mode);
710 // command specific path, we call clear_if_dirty with this
711 let mut my_out = match cmd {
712 "build" => self.cargo_out(compiler, mode, target),
714 // This is the intended out directory for crate documentation.
715 "doc" | "rustdoc" => self.crate_doc_out(target),
717 _ => self.stage_out(compiler, mode),
720 // This is for the original compiler, but if we're forced to use stage 1, then
721 // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
722 // we copy the libs forward.
723 let cmp = if self.force_use_stage1(compiler, target) {
724 self.compiler(1, compiler.host)
729 let libstd_stamp = match cmd {
730 "check" => check::libstd_stamp(self, cmp, target),
731 _ => compile::libstd_stamp(self, cmp, target),
734 let libtest_stamp = match cmd {
735 "check" => check::libtest_stamp(self, cmp, target),
736 _ => compile::libstd_stamp(self, cmp, target),
739 let librustc_stamp = match cmd {
740 "check" => check::librustc_stamp(self, cmp, target),
741 _ => compile::librustc_stamp(self, cmp, target),
744 if cmd == "doc" || cmd == "rustdoc" {
745 if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
746 // This is the intended out directory for compiler documentation.
747 my_out = self.compiler_doc_out(target);
749 let rustdoc = self.rustdoc(compiler.host);
750 self.clear_if_dirty(&my_out, &rustdoc);
751 } else if cmd != "test" {
754 self.clear_if_dirty(&my_out, &self.rustc(compiler));
757 self.clear_if_dirty(&my_out, &libstd_stamp);
760 self.clear_if_dirty(&my_out, &self.rustc(compiler));
761 self.clear_if_dirty(&my_out, &libstd_stamp);
762 self.clear_if_dirty(&my_out, &libtest_stamp);
765 self.clear_if_dirty(&my_out, &librustc_stamp);
767 Mode::ToolBootstrap => { },
769 self.clear_if_dirty(&my_out, &libstd_stamp);
772 self.clear_if_dirty(&my_out, &libstd_stamp);
773 self.clear_if_dirty(&my_out, &libtest_stamp);
776 self.clear_if_dirty(&my_out, &libstd_stamp);
777 self.clear_if_dirty(&my_out, &libtest_stamp);
778 self.clear_if_dirty(&my_out, &librustc_stamp);
784 .env("CARGO_TARGET_DIR", out_dir)
787 if cmd != "install" {
788 cargo.arg("--target")
791 assert_eq!(target, compiler.host);
794 // Set a flag for `check` so that certain build scripts can do less work
795 // (e.g. not building/requiring LLVM).
797 cargo.env("RUST_CHECK", "1");
800 cargo.arg("-j").arg(self.jobs().to_string());
801 // Remove make-related flags to ensure Cargo can correctly set things up
802 cargo.env_remove("MAKEFLAGS");
803 cargo.env_remove("MFLAGS");
805 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
806 // Force cargo to output binaries with disambiguating hashes in the name
807 let metadata = if compiler.stage == 0 {
808 // Treat stage0 like special channel, whether it's a normal prior-
809 // release rustc or a local rebuild with the same version, so we
810 // never mix these libraries by accident.
815 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
818 if compiler.stage == 0 && self.local_rebuild {
819 // Assume the local-rebuild rustc already has stage1 features.
822 stage = compiler.stage;
825 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
827 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
828 if !extra_args.is_empty() {
829 extra_args.push_str(" ");
831 extra_args.push_str(&s);
834 if !extra_args.is_empty() {
839 env::var("RUSTFLAGS").unwrap_or_default(),
845 let want_rustdoc = self.doc_tests != DocTests::No;
847 // We synthetically interpret a stage0 compiler used to build tools as a
848 // "raw" compiler in that it's the exact snapshot we download. Normally
849 // the stage0 build means it uses libraries build by the stage0
850 // compiler, but for tools we just use the precompiled libraries that
852 let use_snapshot = mode == Mode::ToolBootstrap;
853 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
855 let maybe_sysroot = self.sysroot(compiler);
856 let sysroot = if use_snapshot {
857 self.rustc_snapshot_sysroot()
861 let libdir = sysroot.join(libdir(&compiler.host));
863 // Customize the compiler we're running. Specify the compiler to cargo
864 // as our shim and then pass it some various options used to configure
865 // how the actual compiler itself is called.
867 // These variables are primarily all read by
868 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
870 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
871 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
872 .env("RUSTC_REAL", self.rustc(compiler))
873 .env("RUSTC_STAGE", stage.to_string())
875 "RUSTC_DEBUG_ASSERTIONS",
876 self.config.rust_debug_assertions.to_string(),
878 .env("RUSTC_SYSROOT", &sysroot)
879 .env("RUSTC_LIBDIR", &libdir)
880 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
881 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
884 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
885 self.rustdoc(compiler.host)
887 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
890 .env("TEST_MIRI", self.config.test_miri.to_string())
891 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
893 if let Some(host_linker) = self.linker(compiler.host) {
894 cargo.env("RUSTC_HOST_LINKER", host_linker);
896 if let Some(target_linker) = self.linker(target) {
897 cargo.env("RUSTC_TARGET_LINKER", target_linker);
899 if let Some(ref error_format) = self.config.rustc_error_format {
900 cargo.env("RUSTC_ERROR_FORMAT", error_format);
902 if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
903 cargo.env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.config.build));
907 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
908 // enabled in the config. Adding debuginfo makes them several times larger.
909 if self.config.rust_debuginfo_tools {
910 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
912 "RUSTC_DEBUGINFO_LINES",
913 self.config.rust_debuginfo_lines.to_string(),
917 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
919 "RUSTC_DEBUGINFO_LINES",
920 self.config.rust_debuginfo_lines.to_string(),
922 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
924 // Currently the compiler depends on crates from crates.io, and
925 // then other crates can depend on the compiler (e.g. proc-macro
926 // crates). Let's say, for example that rustc itself depends on the
927 // bitflags crate. If an external crate then depends on the
928 // bitflags crate as well, we need to make sure they don't
929 // conflict, even if they pick the same version of bitflags. We'll
930 // want to make sure that e.g. a plugin and rustc each get their
931 // own copy of bitflags.
933 // Cargo ensures that this works in general through the -C metadata
934 // flag. This flag will frob the symbols in the binary to make sure
935 // they're different, even though the source code is the exact
936 // same. To solve this problem for the compiler we extend Cargo's
937 // already-passed -C metadata flag with our own. Our rustc.rs
938 // wrapper around the actual rustc will detect -C metadata being
939 // passed and frob it with this extra string we're passing in.
940 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
943 if let Some(x) = self.crt_static(target) {
944 cargo.env("RUSTC_CRT_STATIC", x.to_string());
947 if let Some(x) = self.crt_static(compiler.host) {
948 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
951 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
952 cargo.env("RUSTC_DEBUGINFO_MAP", map);
955 // Enable usage of unstable features
956 cargo.env("RUSTC_BOOTSTRAP", "1");
957 self.add_rust_test_threads(&mut cargo);
959 // Almost all of the crates that we compile as part of the bootstrap may
960 // have a build script, including the standard library. To compile a
961 // build script, however, it itself needs a standard library! This
962 // introduces a bit of a pickle when we're compiling the standard
965 // To work around this we actually end up using the snapshot compiler
966 // (stage0) for compiling build scripts of the standard library itself.
967 // The stage0 compiler is guaranteed to have a libstd available for use.
969 // For other crates, however, we know that we've already got a standard
970 // library up and running, so we can use the normal compiler to compile
971 // build scripts in that situation.
973 // If LLVM support is disabled we need to use the snapshot compiler to compile
974 // build scripts, as the new compiler doesn't support executables.
975 if mode == Mode::Std || !self.config.llvm_enabled {
977 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
978 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
981 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
982 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
985 if self.config.incremental {
986 cargo.env("CARGO_INCREMENTAL", "1");
989 if let Some(ref on_fail) = self.config.on_fail {
990 cargo.env("RUSTC_ON_FAIL", on_fail);
993 if self.config.print_step_timings {
994 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
997 if self.config.backtrace_on_ice {
998 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1001 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1003 // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
1004 if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) {
1005 cargo.env("RUSTC_DENY_WARNINGS", "1");
1008 // Throughout the build Cargo can execute a number of build scripts
1009 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1010 // obtained previously to those build scripts.
1011 // Build scripts use either the `cc` crate or `configure/make` so we pass
1012 // the options through environment variables that are fetched and understood by both.
1014 // FIXME: the guard against msvc shouldn't need to be here
1015 if target.contains("msvc") {
1016 if let Some(ref cl) = self.config.llvm_clang_cl {
1017 cargo.env("CC", cl).env("CXX", cl);
1020 let ccache = self.config.ccache.as_ref();
1021 let ccacheify = |s: &Path| {
1022 let ccache = match ccache {
1024 None => return s.display().to_string(),
1026 // FIXME: the cc-rs crate only recognizes the literal strings
1027 // `ccache` and `sccache` when doing caching compilations, so we
1028 // mirror that here. It should probably be fixed upstream to
1029 // accept a new env var or otherwise work with custom ccache
1032 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1033 _ => s.display().to_string(),
1036 let cc = ccacheify(&self.cc(target));
1037 cargo.env(format!("CC_{}", target), &cc).env("CC", &cc);
1039 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1041 .env(format!("CFLAGS_{}", target), cflags.clone())
1042 .env("CFLAGS", cflags.clone());
1044 if let Some(ar) = self.ar(target) {
1045 let ranlib = format!("{} s", ar.display());
1047 .env(format!("AR_{}", target), ar)
1049 .env(format!("RANLIB_{}", target), ranlib.clone())
1050 .env("RANLIB", ranlib);
1053 if let Ok(cxx) = self.cxx(target) {
1054 let cxx = ccacheify(&cxx);
1056 .env(format!("CXX_{}", target), &cxx)
1058 .env(format!("CXXFLAGS_{}", target), cflags.clone())
1059 .env("CXXFLAGS", cflags);
1063 if (cmd == "build" || cmd == "rustc")
1064 && mode == Mode::Std
1065 && self.config.extended
1066 && compiler.is_final_stage(self)
1068 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1071 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1072 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1074 // Environment variables *required* throughout the build
1076 // FIXME: should update code to not require this env var
1077 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1079 // Set this for all builds to make sure doc builds also get it.
1080 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1082 // This one's a bit tricky. As of the time of this writing the compiler
1083 // links to the `winapi` crate on crates.io. This crate provides raw
1084 // bindings to Windows system functions, sort of like libc does for
1085 // Unix. This crate also, however, provides "import libraries" for the
1086 // MinGW targets. There's an import library per dll in the windows
1087 // distribution which is what's linked to. These custom import libraries
1088 // are used because the winapi crate can reference Windows functions not
1089 // present in the MinGW import libraries.
1091 // For example MinGW may ship libdbghelp.a, but it may not have
1092 // references to all the functions in the dbghelp dll. Instead the
1093 // custom import library for dbghelp in the winapi crates has all this
1096 // Unfortunately for us though the import libraries are linked by
1097 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1098 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1099 // conflict with the system MinGW ones). This consequently means that
1100 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1101 // DLL) when linked against *again*, for example with procedural macros
1102 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1103 // `-lwinapi_foo` to the linker again. This isn't actually available in
1104 // our distribution, however, so the link fails.
1106 // To solve this problem we tell winapi to not use its bundled import
1107 // libraries. This means that it will link to the system MinGW import
1108 // libraries by default, and the `-ldylib=foo` directives will still get
1109 // passed to the final linker, but they'll look like `-lfoo` which can
1110 // be resolved because MinGW has the import library. The downside is we
1111 // don't get newer functions from Windows, but we don't use any of them
1113 if !mode.is_tool() {
1114 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1117 for _ in 1..self.verbosity {
1121 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1122 (Mode::Std, Some(n), _) |
1123 (Mode::Test, Some(n), _) |
1124 (_, _, Some(n)) => {
1125 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1128 // Don't set anything
1132 if self.config.rust_optimize {
1133 // FIXME: cargo bench/install do not accept `--release`
1134 if cmd != "bench" && cmd != "install" {
1135 cargo.arg("--release");
1139 if self.config.locked_deps {
1140 cargo.arg("--locked");
1142 if self.config.vendor || self.is_sudo {
1143 cargo.arg("--frozen");
1146 self.ci_env.force_coloring_in_ci(&mut cargo);
1151 /// Ensure that a given step is built, returning its output. This will
1152 /// cache the step, so it is safe (and good!) to call this as often as
1153 /// needed to ensure that all dependencies are built.
1154 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1156 let mut stack = self.stack.borrow_mut();
1157 for stack_step in stack.iter() {
1160 .downcast_ref::<S>()
1161 .map_or(true, |stack_step| *stack_step != step)
1165 let mut out = String::new();
1166 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1167 for el in stack.iter().rev() {
1168 out += &format!("\t{:?}\n", el);
1172 if let Some(out) = self.cache.get(&step) {
1173 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1176 let mut graph = self.graph.borrow_mut();
1177 let parent = self.parent.get();
1181 .entry(format!("{:?}", step))
1182 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1183 if let Some(parent) = parent {
1184 graph.add_edge(parent, us, false);
1190 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1191 stack.push(Box::new(step.clone()));
1194 let prev_parent = self.parent.get();
1197 let mut graph = self.graph.borrow_mut();
1198 let parent = self.parent.get();
1202 .entry(format!("{:?}", step))
1203 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1204 self.parent.set(Some(us));
1205 if let Some(parent) = parent {
1206 graph.add_edge(parent, us, true);
1211 let start = Instant::now();
1212 let zero = Duration::new(0, 0);
1213 let parent = self.time_spent_on_dependencies.replace(zero);
1214 let out = step.clone().run(self);
1215 let dur = start.elapsed();
1216 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1220 self.parent.set(prev_parent);
1222 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1224 "[TIMING] {:?} -- {}.{:03}",
1227 dur.subsec_nanos() / 1_000_000
1232 let mut stack = self.stack.borrow_mut();
1233 let cur_step = stack.pop().expect("step stack empty");
1234 assert_eq!(cur_step.downcast_ref(), Some(&step));
1236 self.verbose(&format!(
1238 " ".repeat(self.stack.borrow().len()),
1241 self.cache.put(step, out.clone());
1252 fn configure(host: &[&str], target: &[&str]) -> Config {
1253 let mut config = Config::default_opts();
1254 // don't save toolstates
1255 config.save_toolstates = None;
1256 config.run_host_only = true;
1257 config.dry_run = true;
1258 // try to avoid spurious failures in dist where we create/delete each others file
1259 let dir = config.out.join("tmp-rustbuild-tests").join(
1262 .unwrap_or("unknown")
1265 t!(fs::create_dir_all(&dir));
1267 config.build = INTERNER.intern_str("A");
1268 config.hosts = vec![config.build]
1271 .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1272 .collect::<Vec<_>>();
1273 config.targets = config
1277 .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1278 .collect::<Vec<_>>();
1282 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1283 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1287 fn dist_baseline() {
1288 let build = Build::new(configure(&[], &[]));
1289 let mut builder = Builder::new(&build);
1290 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1292 let a = INTERNER.intern_str("A");
1295 first(builder.cache.all::<dist::Docs>()),
1296 &[dist::Docs { stage: 2, host: a },]
1299 first(builder.cache.all::<dist::Mingw>()),
1300 &[dist::Mingw { host: a },]
1303 first(builder.cache.all::<dist::Rustc>()),
1305 compiler: Compiler { host: a, stage: 2 }
1309 first(builder.cache.all::<dist::Std>()),
1311 compiler: Compiler { host: a, stage: 2 },
1315 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1319 fn dist_with_targets() {
1320 let build = Build::new(configure(&[], &["B"]));
1321 let mut builder = Builder::new(&build);
1322 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1324 let a = INTERNER.intern_str("A");
1325 let b = INTERNER.intern_str("B");
1328 first(builder.cache.all::<dist::Docs>()),
1330 dist::Docs { stage: 2, host: a },
1331 dist::Docs { stage: 2, host: b },
1335 first(builder.cache.all::<dist::Mingw>()),
1336 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1339 first(builder.cache.all::<dist::Rustc>()),
1341 compiler: Compiler { host: a, stage: 2 }
1345 first(builder.cache.all::<dist::Std>()),
1348 compiler: Compiler { host: a, stage: 2 },
1352 compiler: Compiler { host: a, stage: 2 },
1357 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1361 fn dist_with_hosts() {
1362 let build = Build::new(configure(&["B"], &[]));
1363 let mut builder = Builder::new(&build);
1364 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1366 let a = INTERNER.intern_str("A");
1367 let b = INTERNER.intern_str("B");
1370 first(builder.cache.all::<dist::Docs>()),
1372 dist::Docs { stage: 2, host: a },
1373 dist::Docs { stage: 2, host: b },
1377 first(builder.cache.all::<dist::Mingw>()),
1378 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1381 first(builder.cache.all::<dist::Rustc>()),
1384 compiler: Compiler { host: a, stage: 2 }
1387 compiler: Compiler { host: b, stage: 2 }
1392 first(builder.cache.all::<dist::Std>()),
1395 compiler: Compiler { host: a, stage: 2 },
1399 compiler: Compiler { host: a, stage: 2 },
1404 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1408 fn dist_with_targets_and_hosts() {
1409 let build = Build::new(configure(&["B"], &["C"]));
1410 let mut builder = Builder::new(&build);
1411 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1413 let a = INTERNER.intern_str("A");
1414 let b = INTERNER.intern_str("B");
1415 let c = INTERNER.intern_str("C");
1418 first(builder.cache.all::<dist::Docs>()),
1420 dist::Docs { stage: 2, host: a },
1421 dist::Docs { stage: 2, host: b },
1422 dist::Docs { stage: 2, host: c },
1426 first(builder.cache.all::<dist::Mingw>()),
1428 dist::Mingw { host: a },
1429 dist::Mingw { host: b },
1430 dist::Mingw { host: c },
1434 first(builder.cache.all::<dist::Rustc>()),
1437 compiler: Compiler { host: a, stage: 2 }
1440 compiler: Compiler { host: b, stage: 2 }
1445 first(builder.cache.all::<dist::Std>()),
1448 compiler: Compiler { host: a, stage: 2 },
1452 compiler: Compiler { host: a, stage: 2 },
1456 compiler: Compiler { host: a, stage: 2 },
1461 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1465 fn dist_with_target_flag() {
1466 let mut config = configure(&["B"], &["C"]);
1467 config.run_host_only = false; // as-if --target=C was passed
1468 let build = Build::new(config);
1469 let mut builder = Builder::new(&build);
1470 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1472 let a = INTERNER.intern_str("A");
1473 let b = INTERNER.intern_str("B");
1474 let c = INTERNER.intern_str("C");
1477 first(builder.cache.all::<dist::Docs>()),
1479 dist::Docs { stage: 2, host: a },
1480 dist::Docs { stage: 2, host: b },
1481 dist::Docs { stage: 2, host: c },
1485 first(builder.cache.all::<dist::Mingw>()),
1487 dist::Mingw { host: a },
1488 dist::Mingw { host: b },
1489 dist::Mingw { host: c },
1492 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1494 first(builder.cache.all::<dist::Std>()),
1497 compiler: Compiler { host: a, stage: 2 },
1501 compiler: Compiler { host: a, stage: 2 },
1505 compiler: Compiler { host: a, stage: 2 },
1510 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1514 fn dist_with_same_targets_and_hosts() {
1515 let build = Build::new(configure(&["B"], &["B"]));
1516 let mut builder = Builder::new(&build);
1517 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1519 let a = INTERNER.intern_str("A");
1520 let b = INTERNER.intern_str("B");
1523 first(builder.cache.all::<dist::Docs>()),
1525 dist::Docs { stage: 2, host: a },
1526 dist::Docs { stage: 2, host: b },
1530 first(builder.cache.all::<dist::Mingw>()),
1531 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1534 first(builder.cache.all::<dist::Rustc>()),
1537 compiler: Compiler { host: a, stage: 2 }
1540 compiler: Compiler { host: b, stage: 2 }
1545 first(builder.cache.all::<dist::Std>()),
1548 compiler: Compiler { host: a, stage: 2 },
1552 compiler: Compiler { host: a, stage: 2 },
1557 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1559 first(builder.cache.all::<compile::Std>()),
1562 compiler: Compiler { host: a, stage: 0 },
1566 compiler: Compiler { host: a, stage: 1 },
1570 compiler: Compiler { host: a, stage: 2 },
1574 compiler: Compiler { host: a, stage: 1 },
1578 compiler: Compiler { host: a, stage: 2 },
1584 first(builder.cache.all::<compile::Test>()),
1587 compiler: Compiler { host: a, stage: 0 },
1591 compiler: Compiler { host: a, stage: 1 },
1595 compiler: Compiler { host: a, stage: 2 },
1599 compiler: Compiler { host: a, stage: 1 },
1603 compiler: Compiler { host: a, stage: 2 },
1609 first(builder.cache.all::<compile::Assemble>()),
1612 target_compiler: Compiler { host: a, stage: 0 },
1615 target_compiler: Compiler { host: a, stage: 1 },
1618 target_compiler: Compiler { host: a, stage: 2 },
1621 target_compiler: Compiler { host: b, stage: 2 },
1628 fn build_default() {
1629 let build = Build::new(configure(&["B"], &["C"]));
1630 let mut builder = Builder::new(&build);
1631 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1633 let a = INTERNER.intern_str("A");
1634 let b = INTERNER.intern_str("B");
1635 let c = INTERNER.intern_str("C");
1637 assert!(!builder.cache.all::<compile::Std>().is_empty());
1638 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1640 first(builder.cache.all::<compile::Rustc>()),
1643 compiler: Compiler { host: a, stage: 0 },
1647 compiler: Compiler { host: a, stage: 1 },
1651 compiler: Compiler { host: a, stage: 2 },
1655 compiler: Compiler { host: b, stage: 2 },
1659 compiler: Compiler { host: a, stage: 0 },
1663 compiler: Compiler { host: a, stage: 1 },
1667 compiler: Compiler { host: a, stage: 2 },
1671 compiler: Compiler { host: b, stage: 2 },
1678 first(builder.cache.all::<compile::Test>()),
1681 compiler: Compiler { host: a, stage: 0 },
1685 compiler: Compiler { host: a, stage: 1 },
1689 compiler: Compiler { host: a, stage: 2 },
1693 compiler: Compiler { host: b, stage: 2 },
1697 compiler: Compiler { host: a, stage: 0 },
1701 compiler: Compiler { host: a, stage: 1 },
1705 compiler: Compiler { host: a, stage: 2 },
1709 compiler: Compiler { host: b, stage: 2 },
1713 compiler: Compiler { host: a, stage: 2 },
1717 compiler: Compiler { host: b, stage: 2 },
1725 fn build_with_target_flag() {
1726 let mut config = configure(&["B"], &["C"]);
1727 config.run_host_only = false;
1728 let build = Build::new(config);
1729 let mut builder = Builder::new(&build);
1730 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1732 let a = INTERNER.intern_str("A");
1733 let b = INTERNER.intern_str("B");
1734 let c = INTERNER.intern_str("C");
1736 assert!(!builder.cache.all::<compile::Std>().is_empty());
1738 first(builder.cache.all::<compile::Assemble>()),
1741 target_compiler: Compiler { host: a, stage: 0 },
1744 target_compiler: Compiler { host: a, stage: 1 },
1747 target_compiler: Compiler { host: b, stage: 1 },
1750 target_compiler: Compiler { host: a, stage: 2 },
1753 target_compiler: Compiler { host: b, stage: 2 },
1758 first(builder.cache.all::<compile::Rustc>()),
1761 compiler: Compiler { host: a, stage: 0 },
1765 compiler: Compiler { host: a, stage: 1 },
1769 compiler: Compiler { host: a, stage: 0 },
1773 compiler: Compiler { host: a, stage: 1 },
1780 first(builder.cache.all::<compile::Test>()),
1783 compiler: Compiler { host: a, stage: 0 },
1787 compiler: Compiler { host: a, stage: 1 },
1791 compiler: Compiler { host: a, stage: 2 },
1795 compiler: Compiler { host: b, stage: 2 },
1799 compiler: Compiler { host: a, stage: 0 },
1803 compiler: Compiler { host: a, stage: 1 },
1807 compiler: Compiler { host: a, stage: 2 },
1811 compiler: Compiler { host: b, stage: 2 },
1815 compiler: Compiler { host: a, stage: 2 },
1819 compiler: Compiler { host: b, stage: 2 },
1827 fn test_with_no_doc_stage0() {
1828 let mut config = configure(&[], &[]);
1829 config.stage = Some(0);
1830 config.cmd = Subcommand::Test {
1831 paths: vec!["src/libstd".into()],
1835 doc_tests: DocTests::No,
1840 let build = Build::new(config);
1841 let mut builder = Builder::new(&build);
1843 let host = INTERNER.intern_str("A");
1845 builder.run_step_descriptions(
1846 &[StepDescription::from::<test::Crate>()],
1847 &["src/libstd".into()],
1850 // Ensure we don't build any compiler artifacts.
1851 assert!(!builder.cache.contains::<compile::Rustc>());
1853 first(builder.cache.all::<test::Crate>()),
1855 compiler: Compiler { host, stage: 0 },
1858 test_kind: test::TestKind::Test,
1859 krate: INTERNER.intern_str("std"),
1866 let mut config = configure(&[], &[]);
1867 config.exclude = vec![
1868 "src/test/run-pass".into(),
1869 "src/tools/tidy".into(),
1871 config.cmd = Subcommand::Test {
1873 test_args: Vec::new(),
1874 rustc_args: Vec::new(),
1876 doc_tests: DocTests::No,
1881 let build = Build::new(config);
1882 let builder = Builder::new(&build);
1883 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1885 // Ensure we have really excluded run-pass & tidy
1886 assert!(!builder.cache.contains::<test::RunPass>());
1887 assert!(!builder.cache.contains::<test::Tidy>());
1889 // Ensure other tests are not affected.
1890 assert!(builder.cache.contains::<test::RunPassFullDeps>());
1891 assert!(builder.cache.contains::<test::RustdocUi>());