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(_) => 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 // 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!(
384 test::RunPassValgrind,
391 test::RunPassFullDeps,
392 test::RunFailFullDeps,
393 test::CompileFailFullDeps,
394 test::IncrementalFullDeps,
399 test::RunPassValgrindPretty,
400 test::RunPassFullDepsPretty,
401 test::RunFailFullDepsPretty,
411 test::RunMakeFullDeps,
424 // Run bootstrap close to the end as it's unlikely to fail
426 // Run run-make last, since these won't pass without make on Windows
430 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
431 Kind::Doc => describe!(
433 doc::UnstableBookGen,
438 doc::WhitelistedRustc,
449 Kind::Dist => describe!(
454 dist::DebuggerScripts,
458 dist::PlainSourceTarball,
468 Kind::Install => describe!(
482 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
483 let kind = match subcommand {
484 "build" => Kind::Build,
486 "test" => Kind::Test,
487 "bench" => Kind::Bench,
488 "dist" => Kind::Dist,
489 "install" => Kind::Install,
493 let builder = Builder {
495 top_stage: build.config.stage.unwrap_or(2),
498 stack: RefCell::new(Vec::new()),
499 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
501 graph_nodes: RefCell::new(HashMap::new()),
502 graph: RefCell::new(Graph::new()),
503 parent: Cell::new(None),
506 let builder = &builder;
507 let mut should_run = ShouldRun::new(builder);
508 for desc in Builder::get_step_descriptions(builder.kind) {
509 should_run = (desc.should_run)(should_run);
511 let mut help = String::from("Available paths:\n");
512 for pathset in should_run.paths {
513 if let PathSet::Set(set) = pathset {
514 set.iter().for_each(|path| {
516 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
524 pub fn new(build: &Build) -> Builder {
525 let (kind, paths) = match build.config.cmd {
526 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
527 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
528 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
529 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
530 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
531 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
532 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
533 Subcommand::Clean { .. } => panic!(),
536 let builder = Builder {
538 top_stage: build.config.stage.unwrap_or(2),
541 stack: RefCell::new(Vec::new()),
542 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
543 paths: paths.to_owned(),
544 graph_nodes: RefCell::new(HashMap::new()),
545 graph: RefCell::new(Graph::new()),
546 parent: Cell::new(None),
549 if kind == Kind::Dist {
551 !builder.config.test_miri,
552 "Do not distribute with miri enabled.\n\
553 The distributed libraries would include all MIR (increasing binary size).
554 The distributed MIR would include validation statements."
561 pub fn execute_cli(&self) -> Graph<String, bool> {
562 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
563 self.graph.borrow().clone()
566 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
567 let paths = paths.unwrap_or(&[]);
568 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
571 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
572 StepDescription::run(v, self, paths);
575 /// Obtain a compiler at a given stage and for a given host. Explicitly does
576 /// not take `Compiler` since all `Compiler` instances are meant to be
577 /// obtained through this function, since it ensures that they are valid
578 /// (i.e., built and assembled).
579 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
580 self.ensure(compile::Assemble {
581 target_compiler: Compiler { stage, host },
585 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
586 self.ensure(compile::Sysroot { compiler })
589 /// Returns the libdir where the standard library and other artifacts are
590 /// found for a compiler's sysroot.
591 pub fn sysroot_libdir(
594 target: Interned<String>,
595 ) -> Interned<PathBuf> {
596 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
599 target: Interned<String>,
601 impl Step for Libdir {
602 type Output = Interned<PathBuf>;
604 fn should_run(run: ShouldRun) -> ShouldRun {
608 fn run(self, builder: &Builder) -> Interned<PathBuf> {
609 let compiler = self.compiler;
610 let config = &builder.build.config;
611 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
612 builder.build.config.libdir_relative().unwrap()
616 let sysroot = builder
617 .sysroot(self.compiler)
622 let _ = fs::remove_dir_all(&sysroot);
623 t!(fs::create_dir_all(&sysroot));
624 INTERNER.intern_path(sysroot)
627 self.ensure(Libdir { compiler, target })
630 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
631 self.sysroot_libdir(compiler, compiler.host)
632 .with_file_name(self.config.rust_codegen_backends_dir.clone())
635 /// Returns the compiler's libdir where it stores the dynamic libraries that
636 /// it itself links against.
638 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
640 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
641 if compiler.is_snapshot(self) {
642 self.rustc_snapshot_libdir()
644 self.sysroot(compiler).join(libdir(&compiler.host))
648 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
649 /// library lookup path.
650 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
651 // Windows doesn't need dylib path munging because the dlls for the
652 // compiler live next to the compiler and the system will find them
658 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
661 /// Get a path to the compiler specified.
662 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
663 if compiler.is_snapshot(self) {
664 self.initial_rustc.clone()
666 self.sysroot(compiler)
668 .join(exe("rustc", &compiler.host))
672 pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
673 self.ensure(tool::Rustdoc { host })
676 pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
677 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
678 let compiler = self.compiler(self.top_stage, host);
679 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
680 .env("RUSTC_SYSROOT", self.sysroot(compiler))
683 self.sysroot_libdir(compiler, self.config.build),
685 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
686 .env("RUSTDOC_REAL", self.rustdoc(host))
687 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
688 .env("RUSTC_BOOTSTRAP", "1");
689 if let Some(linker) = self.linker(host) {
690 cmd.env("RUSTC_TARGET_LINKER", linker);
695 /// Prepares an invocation of `cargo` to be run.
697 /// This will create a `Command` that represents a pending execution of
698 /// Cargo. This cargo will be configured to use `compiler` as the actual
699 /// rustc compiler, its output will be scoped by `mode`'s output directory,
700 /// it will pass the `--target` flag for the specified `target`, and will be
701 /// executing the Cargo command `cmd`.
706 target: Interned<String>,
709 let mut cargo = Command::new(&self.initial_cargo);
710 let out_dir = self.stage_out(compiler, mode);
712 // command specific path, we call clear_if_dirty with this
713 let mut my_out = match cmd {
714 "build" => self.cargo_out(compiler, mode, target),
716 // This is the intended out directory for crate documentation.
717 "doc" => self.crate_doc_out(target),
719 _ => self.stage_out(compiler, mode),
722 // This is for the original compiler, but if we're forced to use stage 1, then
723 // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
724 // we copy the libs forward.
725 let cmp = if self.force_use_stage1(compiler, target) {
726 self.compiler(1, compiler.host)
731 let libstd_stamp = match cmd {
732 "check" => check::libstd_stamp(self, cmp, target),
733 _ => compile::libstd_stamp(self, cmp, target),
736 let libtest_stamp = match cmd {
737 "check" => check::libtest_stamp(self, cmp, target),
738 _ => compile::libstd_stamp(self, cmp, target),
741 let librustc_stamp = match cmd {
742 "check" => check::librustc_stamp(self, cmp, target),
743 _ => compile::librustc_stamp(self, cmp, target),
747 if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
748 // This is the intended out directory for compiler documentation.
749 my_out = self.compiler_doc_out(target);
751 let rustdoc = self.rustdoc(compiler.host);
752 self.clear_if_dirty(&my_out, &rustdoc);
753 } else if cmd != "test" {
756 self.clear_if_dirty(&my_out, &self.rustc(compiler));
759 self.clear_if_dirty(&my_out, &libstd_stamp);
762 self.clear_if_dirty(&my_out, &self.rustc(compiler));
763 self.clear_if_dirty(&my_out, &libstd_stamp);
764 self.clear_if_dirty(&my_out, &libtest_stamp);
767 self.clear_if_dirty(&my_out, &librustc_stamp);
769 Mode::ToolBootstrap => { },
771 self.clear_if_dirty(&my_out, &libstd_stamp);
774 self.clear_if_dirty(&my_out, &libstd_stamp);
775 self.clear_if_dirty(&my_out, &libtest_stamp);
778 self.clear_if_dirty(&my_out, &libstd_stamp);
779 self.clear_if_dirty(&my_out, &libtest_stamp);
780 self.clear_if_dirty(&my_out, &librustc_stamp);
786 .env("CARGO_TARGET_DIR", out_dir)
789 if cmd != "install" {
790 cargo.arg("--target")
793 assert_eq!(target, compiler.host);
796 // Set a flag for `check` so that certain build scripts can do less work
797 // (e.g. not building/requiring LLVM).
799 cargo.env("RUST_CHECK", "1");
802 cargo.arg("-j").arg(self.jobs().to_string());
803 // Remove make-related flags to ensure Cargo can correctly set things up
804 cargo.env_remove("MAKEFLAGS");
805 cargo.env_remove("MFLAGS");
807 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
808 // Force cargo to output binaries with disambiguating hashes in the name
809 let metadata = if compiler.stage == 0 {
810 // Treat stage0 like special channel, whether it's a normal prior-
811 // release rustc or a local rebuild with the same version, so we
812 // never mix these libraries by accident.
817 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
820 if compiler.stage == 0 && self.local_rebuild {
821 // Assume the local-rebuild rustc already has stage1 features.
824 stage = compiler.stage;
827 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
829 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
830 if !extra_args.is_empty() {
831 extra_args.push_str(" ");
833 extra_args.push_str(&s);
836 if !extra_args.is_empty() {
841 env::var("RUSTFLAGS").unwrap_or_default(),
847 let want_rustdoc = self.doc_tests != DocTests::No;
849 // We synthetically interpret a stage0 compiler used to build tools as a
850 // "raw" compiler in that it's the exact snapshot we download. Normally
851 // the stage0 build means it uses libraries build by the stage0
852 // compiler, but for tools we just use the precompiled libraries that
854 let use_snapshot = mode == Mode::ToolBootstrap;
855 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
857 let maybe_sysroot = self.sysroot(compiler);
858 let sysroot = if use_snapshot {
859 self.rustc_snapshot_sysroot()
863 let libdir = sysroot.join(libdir(&compiler.host));
865 // Customize the compiler we're running. Specify the compiler to cargo
866 // as our shim and then pass it some various options used to configure
867 // how the actual compiler itself is called.
869 // These variables are primarily all read by
870 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
872 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
873 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
874 .env("RUSTC_REAL", self.rustc(compiler))
875 .env("RUSTC_STAGE", stage.to_string())
877 "RUSTC_DEBUG_ASSERTIONS",
878 self.config.rust_debug_assertions.to_string(),
880 .env("RUSTC_SYSROOT", &sysroot)
881 .env("RUSTC_LIBDIR", &libdir)
882 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
883 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
886 if cmd == "doc" || (cmd == "test" && want_rustdoc) {
887 self.rustdoc(compiler.host)
889 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
892 .env("TEST_MIRI", self.config.test_miri.to_string())
893 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
895 if let Some(host_linker) = self.linker(compiler.host) {
896 cargo.env("RUSTC_HOST_LINKER", host_linker);
898 if let Some(target_linker) = self.linker(target) {
899 cargo.env("RUSTC_TARGET_LINKER", target_linker);
901 if let Some(ref error_format) = self.config.rustc_error_format {
902 cargo.env("RUSTC_ERROR_FORMAT", error_format);
904 if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
905 cargo.env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.config.build));
909 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
910 // enabled in the config. Adding debuginfo makes them several times larger.
911 if self.config.rust_debuginfo_tools {
912 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
914 "RUSTC_DEBUGINFO_LINES",
915 self.config.rust_debuginfo_lines.to_string(),
919 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
921 "RUSTC_DEBUGINFO_LINES",
922 self.config.rust_debuginfo_lines.to_string(),
924 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
926 // Currently the compiler depends on crates from crates.io, and
927 // then other crates can depend on the compiler (e.g. proc-macro
928 // crates). Let's say, for example that rustc itself depends on the
929 // bitflags crate. If an external crate then depends on the
930 // bitflags crate as well, we need to make sure they don't
931 // conflict, even if they pick the same version of bitflags. We'll
932 // want to make sure that e.g. a plugin and rustc each get their
933 // own copy of bitflags.
935 // Cargo ensures that this works in general through the -C metadata
936 // flag. This flag will frob the symbols in the binary to make sure
937 // they're different, even though the source code is the exact
938 // same. To solve this problem for the compiler we extend Cargo's
939 // already-passed -C metadata flag with our own. Our rustc.rs
940 // wrapper around the actual rustc will detect -C metadata being
941 // passed and frob it with this extra string we're passing in.
942 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
945 if let Some(x) = self.crt_static(target) {
946 cargo.env("RUSTC_CRT_STATIC", x.to_string());
949 if let Some(x) = self.crt_static(compiler.host) {
950 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
953 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
954 cargo.env("RUSTC_DEBUGINFO_MAP", map);
957 // Enable usage of unstable features
958 cargo.env("RUSTC_BOOTSTRAP", "1");
959 self.add_rust_test_threads(&mut cargo);
961 // Almost all of the crates that we compile as part of the bootstrap may
962 // have a build script, including the standard library. To compile a
963 // build script, however, it itself needs a standard library! This
964 // introduces a bit of a pickle when we're compiling the standard
967 // To work around this we actually end up using the snapshot compiler
968 // (stage0) for compiling build scripts of the standard library itself.
969 // The stage0 compiler is guaranteed to have a libstd available for use.
971 // For other crates, however, we know that we've already got a standard
972 // library up and running, so we can use the normal compiler to compile
973 // build scripts in that situation.
975 // If LLVM support is disabled we need to use the snapshot compiler to compile
976 // build scripts, as the new compiler doesn't support executables.
977 if mode == Mode::Std || !self.config.llvm_enabled {
979 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
980 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
983 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
984 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
987 if self.config.incremental {
988 cargo.env("CARGO_INCREMENTAL", "1");
991 if let Some(ref on_fail) = self.config.on_fail {
992 cargo.env("RUSTC_ON_FAIL", on_fail);
995 if self.config.print_step_timings {
996 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
999 if self.config.backtrace_on_ice {
1000 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1003 if self.config.rust_verify_llvm_ir {
1004 cargo.env("RUSTC_VERIFY_LLVM_IR", "1");
1007 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1009 // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
1010 if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) {
1011 cargo.env("RUSTC_DENY_WARNINGS", "1");
1014 // Throughout the build Cargo can execute a number of build scripts
1015 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1016 // obtained previously to those build scripts.
1017 // Build scripts use either the `cc` crate or `configure/make` so we pass
1018 // the options through environment variables that are fetched and understood by both.
1020 // FIXME: the guard against msvc shouldn't need to be here
1021 if target.contains("msvc") {
1022 if let Some(ref cl) = self.config.llvm_clang_cl {
1023 cargo.env("CC", cl).env("CXX", cl);
1026 let ccache = self.config.ccache.as_ref();
1027 let ccacheify = |s: &Path| {
1028 let ccache = match ccache {
1030 None => return s.display().to_string(),
1032 // FIXME: the cc-rs crate only recognizes the literal strings
1033 // `ccache` and `sccache` when doing caching compilations, so we
1034 // mirror that here. It should probably be fixed upstream to
1035 // accept a new env var or otherwise work with custom ccache
1038 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1039 _ => s.display().to_string(),
1042 let cc = ccacheify(&self.cc(target));
1043 cargo.env(format!("CC_{}", target), &cc).env("CC", &cc);
1045 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1047 .env(format!("CFLAGS_{}", target), cflags.clone())
1048 .env("CFLAGS", cflags.clone());
1050 if let Some(ar) = self.ar(target) {
1051 let ranlib = format!("{} s", ar.display());
1053 .env(format!("AR_{}", target), ar)
1055 .env(format!("RANLIB_{}", target), ranlib.clone())
1056 .env("RANLIB", ranlib);
1059 if let Ok(cxx) = self.cxx(target) {
1060 let cxx = ccacheify(&cxx);
1062 .env(format!("CXX_{}", target), &cxx)
1064 .env(format!("CXXFLAGS_{}", target), cflags.clone())
1065 .env("CXXFLAGS", cflags);
1069 if (cmd == "build" || cmd == "rustc")
1070 && mode == Mode::Std
1071 && self.config.extended
1072 && compiler.is_final_stage(self)
1074 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1077 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1078 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1080 // Environment variables *required* throughout the build
1082 // FIXME: should update code to not require this env var
1083 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1085 // Set this for all builds to make sure doc builds also get it.
1086 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1088 // This one's a bit tricky. As of the time of this writing the compiler
1089 // links to the `winapi` crate on crates.io. This crate provides raw
1090 // bindings to Windows system functions, sort of like libc does for
1091 // Unix. This crate also, however, provides "import libraries" for the
1092 // MinGW targets. There's an import library per dll in the windows
1093 // distribution which is what's linked to. These custom import libraries
1094 // are used because the winapi crate can reference Windows functions not
1095 // present in the MinGW import libraries.
1097 // For example MinGW may ship libdbghelp.a, but it may not have
1098 // references to all the functions in the dbghelp dll. Instead the
1099 // custom import library for dbghelp in the winapi crates has all this
1102 // Unfortunately for us though the import libraries are linked by
1103 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1104 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1105 // conflict with the system MinGW ones). This consequently means that
1106 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1107 // DLL) when linked against *again*, for example with procedural macros
1108 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1109 // `-lwinapi_foo` to the linker again. This isn't actually available in
1110 // our distribution, however, so the link fails.
1112 // To solve this problem we tell winapi to not use its bundled import
1113 // libraries. This means that it will link to the system MinGW import
1114 // libraries by default, and the `-ldylib=foo` directives will still get
1115 // passed to the final linker, but they'll look like `-lfoo` which can
1116 // be resolved because MinGW has the import library. The downside is we
1117 // don't get newer functions from Windows, but we don't use any of them
1119 if !mode.is_tool() {
1120 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1123 for _ in 1..self.verbosity {
1127 // This must be kept before the thinlto check, as we set codegen units
1128 // to 1 forcibly there.
1129 if let Some(n) = self.config.rust_codegen_units {
1130 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1133 if self.config.rust_optimize {
1134 // FIXME: cargo bench/install do not accept `--release`
1135 if cmd != "bench" && cmd != "install" {
1136 cargo.arg("--release");
1140 if self.config.locked_deps {
1141 cargo.arg("--locked");
1143 if self.config.vendor || self.is_sudo {
1144 cargo.arg("--frozen");
1147 self.ci_env.force_coloring_in_ci(&mut cargo);
1152 /// Ensure that a given step is built, returning its output. This will
1153 /// cache the step, so it is safe (and good!) to call this as often as
1154 /// needed to ensure that all dependencies are built.
1155 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1157 let mut stack = self.stack.borrow_mut();
1158 for stack_step in stack.iter() {
1161 .downcast_ref::<S>()
1162 .map_or(true, |stack_step| *stack_step != step)
1166 let mut out = String::new();
1167 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1168 for el in stack.iter().rev() {
1169 out += &format!("\t{:?}\n", el);
1173 if let Some(out) = self.cache.get(&step) {
1174 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1177 let mut graph = self.graph.borrow_mut();
1178 let parent = self.parent.get();
1182 .entry(format!("{:?}", step))
1183 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1184 if let Some(parent) = parent {
1185 graph.add_edge(parent, us, false);
1191 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1192 stack.push(Box::new(step.clone()));
1195 let prev_parent = self.parent.get();
1198 let mut graph = self.graph.borrow_mut();
1199 let parent = self.parent.get();
1203 .entry(format!("{:?}", step))
1204 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1205 self.parent.set(Some(us));
1206 if let Some(parent) = parent {
1207 graph.add_edge(parent, us, true);
1212 let start = Instant::now();
1213 let zero = Duration::new(0, 0);
1214 let parent = self.time_spent_on_dependencies.replace(zero);
1215 let out = step.clone().run(self);
1216 let dur = start.elapsed();
1217 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1221 self.parent.set(prev_parent);
1223 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1225 "[TIMING] {:?} -- {}.{:03}",
1228 dur.subsec_nanos() / 1_000_000
1233 let mut stack = self.stack.borrow_mut();
1234 let cur_step = stack.pop().expect("step stack empty");
1235 assert_eq!(cur_step.downcast_ref(), Some(&step));
1237 self.verbose(&format!(
1239 " ".repeat(self.stack.borrow().len()),
1242 self.cache.put(step, out.clone());
1253 fn configure(host: &[&str], target: &[&str]) -> Config {
1254 let mut config = Config::default_opts();
1255 // don't save toolstates
1256 config.save_toolstates = None;
1257 config.run_host_only = true;
1258 config.dry_run = true;
1259 // try to avoid spurious failures in dist where we create/delete each others file
1260 let dir = config.out.join("tmp-rustbuild-tests").join(
1263 .unwrap_or("unknown")
1266 t!(fs::create_dir_all(&dir));
1268 config.build = INTERNER.intern_str("A");
1269 config.hosts = vec![config.build]
1272 .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1273 .collect::<Vec<_>>();
1274 config.targets = config
1278 .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1279 .collect::<Vec<_>>();
1283 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1284 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1288 fn dist_baseline() {
1289 let build = Build::new(configure(&[], &[]));
1290 let mut builder = Builder::new(&build);
1291 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1293 let a = INTERNER.intern_str("A");
1296 first(builder.cache.all::<dist::Docs>()),
1297 &[dist::Docs { stage: 2, host: a },]
1300 first(builder.cache.all::<dist::Mingw>()),
1301 &[dist::Mingw { host: a },]
1304 first(builder.cache.all::<dist::Rustc>()),
1306 compiler: Compiler { host: a, stage: 2 }
1310 first(builder.cache.all::<dist::Std>()),
1312 compiler: Compiler { host: a, stage: 2 },
1316 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1320 fn dist_with_targets() {
1321 let build = Build::new(configure(&[], &["B"]));
1322 let mut builder = Builder::new(&build);
1323 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1325 let a = INTERNER.intern_str("A");
1326 let b = INTERNER.intern_str("B");
1329 first(builder.cache.all::<dist::Docs>()),
1331 dist::Docs { stage: 2, host: a },
1332 dist::Docs { stage: 2, host: b },
1336 first(builder.cache.all::<dist::Mingw>()),
1337 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1340 first(builder.cache.all::<dist::Rustc>()),
1342 compiler: Compiler { host: a, stage: 2 }
1346 first(builder.cache.all::<dist::Std>()),
1349 compiler: Compiler { host: a, stage: 2 },
1353 compiler: Compiler { host: a, stage: 2 },
1358 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1362 fn dist_with_hosts() {
1363 let build = Build::new(configure(&["B"], &[]));
1364 let mut builder = Builder::new(&build);
1365 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1367 let a = INTERNER.intern_str("A");
1368 let b = INTERNER.intern_str("B");
1371 first(builder.cache.all::<dist::Docs>()),
1373 dist::Docs { stage: 2, host: a },
1374 dist::Docs { stage: 2, host: b },
1378 first(builder.cache.all::<dist::Mingw>()),
1379 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1382 first(builder.cache.all::<dist::Rustc>()),
1385 compiler: Compiler { host: a, stage: 2 }
1388 compiler: Compiler { host: b, stage: 2 }
1393 first(builder.cache.all::<dist::Std>()),
1396 compiler: Compiler { host: a, stage: 2 },
1400 compiler: Compiler { host: a, stage: 2 },
1405 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1409 fn dist_with_targets_and_hosts() {
1410 let build = Build::new(configure(&["B"], &["C"]));
1411 let mut builder = Builder::new(&build);
1412 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1414 let a = INTERNER.intern_str("A");
1415 let b = INTERNER.intern_str("B");
1416 let c = INTERNER.intern_str("C");
1419 first(builder.cache.all::<dist::Docs>()),
1421 dist::Docs { stage: 2, host: a },
1422 dist::Docs { stage: 2, host: b },
1423 dist::Docs { stage: 2, host: c },
1427 first(builder.cache.all::<dist::Mingw>()),
1429 dist::Mingw { host: a },
1430 dist::Mingw { host: b },
1431 dist::Mingw { host: c },
1435 first(builder.cache.all::<dist::Rustc>()),
1438 compiler: Compiler { host: a, stage: 2 }
1441 compiler: Compiler { host: b, stage: 2 }
1446 first(builder.cache.all::<dist::Std>()),
1449 compiler: Compiler { host: a, stage: 2 },
1453 compiler: Compiler { host: a, stage: 2 },
1457 compiler: Compiler { host: a, stage: 2 },
1462 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1466 fn dist_with_target_flag() {
1467 let mut config = configure(&["B"], &["C"]);
1468 config.run_host_only = false; // as-if --target=C was passed
1469 let build = Build::new(config);
1470 let mut builder = Builder::new(&build);
1471 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1473 let a = INTERNER.intern_str("A");
1474 let b = INTERNER.intern_str("B");
1475 let c = INTERNER.intern_str("C");
1478 first(builder.cache.all::<dist::Docs>()),
1480 dist::Docs { stage: 2, host: a },
1481 dist::Docs { stage: 2, host: b },
1482 dist::Docs { stage: 2, host: c },
1486 first(builder.cache.all::<dist::Mingw>()),
1488 dist::Mingw { host: a },
1489 dist::Mingw { host: b },
1490 dist::Mingw { host: c },
1493 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1495 first(builder.cache.all::<dist::Std>()),
1498 compiler: Compiler { host: a, stage: 2 },
1502 compiler: Compiler { host: a, stage: 2 },
1506 compiler: Compiler { host: a, stage: 2 },
1511 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1515 fn dist_with_same_targets_and_hosts() {
1516 let build = Build::new(configure(&["B"], &["B"]));
1517 let mut builder = Builder::new(&build);
1518 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1520 let a = INTERNER.intern_str("A");
1521 let b = INTERNER.intern_str("B");
1524 first(builder.cache.all::<dist::Docs>()),
1526 dist::Docs { stage: 2, host: a },
1527 dist::Docs { stage: 2, host: b },
1531 first(builder.cache.all::<dist::Mingw>()),
1532 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1535 first(builder.cache.all::<dist::Rustc>()),
1538 compiler: Compiler { host: a, stage: 2 }
1541 compiler: Compiler { host: b, stage: 2 }
1546 first(builder.cache.all::<dist::Std>()),
1549 compiler: Compiler { host: a, stage: 2 },
1553 compiler: Compiler { host: a, stage: 2 },
1558 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1560 first(builder.cache.all::<compile::Std>()),
1563 compiler: Compiler { host: a, stage: 0 },
1567 compiler: Compiler { host: a, stage: 1 },
1571 compiler: Compiler { host: a, stage: 2 },
1575 compiler: Compiler { host: a, stage: 1 },
1579 compiler: Compiler { host: a, stage: 2 },
1585 first(builder.cache.all::<compile::Test>()),
1588 compiler: Compiler { host: a, stage: 0 },
1592 compiler: Compiler { host: a, stage: 1 },
1596 compiler: Compiler { host: a, stage: 2 },
1600 compiler: Compiler { host: a, stage: 1 },
1604 compiler: Compiler { host: a, stage: 2 },
1610 first(builder.cache.all::<compile::Assemble>()),
1613 target_compiler: Compiler { host: a, stage: 0 },
1616 target_compiler: Compiler { host: a, stage: 1 },
1619 target_compiler: Compiler { host: a, stage: 2 },
1622 target_compiler: Compiler { host: b, stage: 2 },
1629 fn build_default() {
1630 let build = Build::new(configure(&["B"], &["C"]));
1631 let mut builder = Builder::new(&build);
1632 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1634 let a = INTERNER.intern_str("A");
1635 let b = INTERNER.intern_str("B");
1636 let c = INTERNER.intern_str("C");
1638 assert!(!builder.cache.all::<compile::Std>().is_empty());
1639 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1641 first(builder.cache.all::<compile::Rustc>()),
1644 compiler: Compiler { host: a, stage: 0 },
1648 compiler: Compiler { host: a, stage: 1 },
1652 compiler: Compiler { host: a, stage: 2 },
1656 compiler: Compiler { host: b, stage: 2 },
1660 compiler: Compiler { host: a, stage: 0 },
1664 compiler: Compiler { host: a, stage: 1 },
1668 compiler: Compiler { host: a, stage: 2 },
1672 compiler: Compiler { host: b, stage: 2 },
1679 first(builder.cache.all::<compile::Test>()),
1682 compiler: Compiler { host: a, stage: 0 },
1686 compiler: Compiler { host: a, stage: 1 },
1690 compiler: Compiler { host: a, stage: 2 },
1694 compiler: Compiler { host: b, stage: 2 },
1698 compiler: Compiler { host: a, stage: 0 },
1702 compiler: Compiler { host: a, stage: 1 },
1706 compiler: Compiler { host: a, stage: 2 },
1710 compiler: Compiler { host: b, stage: 2 },
1714 compiler: Compiler { host: a, stage: 2 },
1718 compiler: Compiler { host: b, stage: 2 },
1726 fn build_with_target_flag() {
1727 let mut config = configure(&["B"], &["C"]);
1728 config.run_host_only = false;
1729 let build = Build::new(config);
1730 let mut builder = Builder::new(&build);
1731 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1733 let a = INTERNER.intern_str("A");
1734 let b = INTERNER.intern_str("B");
1735 let c = INTERNER.intern_str("C");
1737 assert!(!builder.cache.all::<compile::Std>().is_empty());
1739 first(builder.cache.all::<compile::Assemble>()),
1742 target_compiler: Compiler { host: a, stage: 0 },
1745 target_compiler: Compiler { host: a, stage: 1 },
1748 target_compiler: Compiler { host: b, stage: 1 },
1751 target_compiler: Compiler { host: a, stage: 2 },
1754 target_compiler: Compiler { host: b, stage: 2 },
1759 first(builder.cache.all::<compile::Rustc>()),
1762 compiler: Compiler { host: a, stage: 0 },
1766 compiler: Compiler { host: a, stage: 1 },
1770 compiler: Compiler { host: a, stage: 0 },
1774 compiler: Compiler { host: a, stage: 1 },
1781 first(builder.cache.all::<compile::Test>()),
1784 compiler: Compiler { host: a, stage: 0 },
1788 compiler: Compiler { host: a, stage: 1 },
1792 compiler: Compiler { host: a, stage: 2 },
1796 compiler: Compiler { host: b, stage: 2 },
1800 compiler: Compiler { host: a, stage: 0 },
1804 compiler: Compiler { host: a, stage: 1 },
1808 compiler: Compiler { host: a, stage: 2 },
1812 compiler: Compiler { host: b, stage: 2 },
1816 compiler: Compiler { host: a, stage: 2 },
1820 compiler: Compiler { host: b, stage: 2 },
1828 fn test_with_no_doc_stage0() {
1829 let mut config = configure(&[], &[]);
1830 config.stage = Some(0);
1831 config.cmd = Subcommand::Test {
1832 paths: vec!["src/libstd".into()],
1836 doc_tests: DocTests::No,
1841 let build = Build::new(config);
1842 let mut builder = Builder::new(&build);
1844 let host = INTERNER.intern_str("A");
1846 builder.run_step_descriptions(
1847 &[StepDescription::from::<test::Crate>()],
1848 &["src/libstd".into()],
1851 // Ensure we don't build any compiler artifacts.
1852 assert!(builder.cache.all::<compile::Rustc>().is_empty());
1854 first(builder.cache.all::<test::Crate>()),
1856 compiler: Compiler { host, stage: 0 },
1859 test_kind: test::TestKind::Test,
1860 krate: INTERNER.intern_str("std"),