2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::collections::HashMap;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
14 use crate::cache::{Cache, Interned, INTERNER};
19 use crate::flags::Subcommand;
24 use crate::util::{self, add_lib_path, exe, libdir};
25 use crate::{Build, DocTests, Mode, GitRepo};
27 pub use crate::Compiler;
29 use petgraph::graph::NodeIndex;
32 pub struct Builder<'a> {
37 stack: RefCell<Vec<Box<dyn Any>>>,
38 time_spent_on_dependencies: Cell<Duration>,
39 pub paths: Vec<PathBuf>,
40 graph_nodes: RefCell<HashMap<String, NodeIndex>>,
41 graph: RefCell<Graph<String, bool>>,
42 parent: Cell<Option<NodeIndex>>,
45 impl<'a> Deref for Builder<'a> {
48 fn deref(&self) -> &Self::Target {
53 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
54 /// `PathBuf` when directories are created or to return a `Compiler` once
55 /// it's been assembled.
58 const DEFAULT: bool = false;
60 /// Run this rule for all hosts without cross compiling.
61 const ONLY_HOSTS: bool = false;
63 /// Primary function to execute this rule. Can call `builder.ensure(...)`
64 /// with other steps to run those.
65 fn run(self, builder: &Builder) -> Self::Output;
67 /// When bootstrap is passed a set of paths, this controls whether this rule
68 /// will execute. However, it does not get called in a "default" context
69 /// when we are not passed any paths; in that case, make_run is called
71 fn should_run(run: ShouldRun) -> ShouldRun;
73 /// Build up a "root" rule, either as a default rule or from a path passed
76 /// When path is `None`, we are executing in a context where no paths were
77 /// passed. When `./x.py build` is run, for example, this rule could get
78 /// called if it is in the correct list below with a path of `None`.
79 fn make_run(_run: RunConfig) {
80 // It is reasonable to not have an implementation of make_run for rules
81 // who do not want to get called from the root context. This means that
82 // they are likely dependencies (e.g., sysroot creation) or similar, and
83 // as such calling them from ./x.py isn't logical.
88 pub struct RunConfig<'a> {
89 pub builder: &'a Builder<'a>,
90 pub host: Interned<String>,
91 pub target: Interned<String>,
95 struct StepDescription {
98 should_run: fn(ShouldRun) -> ShouldRun,
99 make_run: fn(RunConfig),
103 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
105 Set(BTreeSet<PathBuf>),
110 fn empty() -> PathSet {
111 PathSet::Set(BTreeSet::new())
114 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
115 let mut set = BTreeSet::new();
116 set.insert(path.into());
120 fn has(&self, needle: &Path) -> bool {
122 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
123 PathSet::Suite(suite) => suite.ends_with(needle),
127 fn path(&self, builder: &Builder) -> PathBuf {
129 PathSet::Set(set) => set
132 .unwrap_or(&builder.build.src)
134 PathSet::Suite(path) => PathBuf::from(path),
139 impl StepDescription {
140 fn from<S: Step>() -> StepDescription {
143 only_hosts: S::ONLY_HOSTS,
144 should_run: S::should_run,
145 make_run: S::make_run,
146 name: unsafe { ::std::intrinsics::type_name::<S>() },
150 fn maybe_run(&self, builder: &Builder, pathset: &PathSet) {
151 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
152 eprintln!("Skipping {:?} because it is excluded", pathset);
154 } else if !builder.config.exclude.is_empty() {
156 "{:?} not skipped for {:?} -- not in {:?}",
157 pathset, self.name, builder.config.exclude
160 let hosts = &builder.hosts;
162 // Determine the targets participating in this rule.
163 let targets = if self.only_hosts {
164 if !builder.config.run_host_only {
165 return; // don't run anything
174 for target in targets {
175 let run = RunConfig {
177 path: pathset.path(builder),
181 (self.make_run)(run);
186 fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
189 .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
190 .collect::<Vec<_>>();
192 // sanity checks on rules
193 for (desc, should_run) in v.iter().zip(&should_runs) {
195 !should_run.paths.is_empty(),
196 "{:?} should have at least one pathset",
201 if paths.is_empty() {
202 for (desc, should_run) in v.iter().zip(should_runs) {
203 if desc.default && should_run.is_really_default {
204 for pathset in &should_run.paths {
205 desc.maybe_run(builder, pathset);
211 // strip CurDir prefix if present
212 let path = match path.strip_prefix(".") {
217 let mut attempted_run = false;
218 for (desc, should_run) in v.iter().zip(&should_runs) {
219 if let Some(suite) = should_run.is_suite_path(path) {
220 attempted_run = true;
221 desc.maybe_run(builder, suite);
222 } else if let Some(pathset) = should_run.pathset_for_path(path) {
223 attempted_run = true;
224 desc.maybe_run(builder, pathset);
229 panic!("Error: no rules matched {}.", path.display());
237 pub struct ShouldRun<'a> {
238 pub builder: &'a Builder<'a>,
239 // use a BTreeSet to maintain sort order
240 paths: BTreeSet<PathSet>,
242 // If this is a default rule, this is an additional constraint placed on
243 // its run. Generally something like compiler docs being enabled.
244 is_really_default: bool,
247 impl<'a> ShouldRun<'a> {
248 fn new(builder: &'a Builder) -> ShouldRun<'a> {
251 paths: BTreeSet::new(),
252 is_really_default: true, // by default no additional conditions
256 pub fn default_condition(mut self, cond: bool) -> Self {
257 self.is_really_default = cond;
261 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
262 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
263 // actually doing something different for every crate passed.
264 pub fn all_krates(mut self, name: &str) -> Self {
265 let mut set = BTreeSet::new();
266 for krate in self.builder.in_tree_crates(name) {
267 set.insert(PathBuf::from(&krate.path));
269 self.paths.insert(PathSet::Set(set));
273 pub fn krate(mut self, name: &str) -> Self {
274 for krate in self.builder.in_tree_crates(name) {
275 self.paths.insert(PathSet::one(&krate.path));
280 // single, non-aliased path
281 pub fn path(self, path: &str) -> Self {
285 // multiple aliases for the same job
286 pub fn paths(mut self, paths: &[&str]) -> Self {
288 .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
292 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
293 self.paths.iter().find(|pathset| match pathset {
294 PathSet::Suite(p) => path.starts_with(p),
295 PathSet::Set(_) => false,
299 pub fn suite_path(mut self, suite: &str) -> Self {
300 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
304 // allows being more explicit about why should_run in Step returns the value passed to it
305 pub fn never(mut self) -> ShouldRun<'a> {
306 self.paths.insert(PathSet::empty());
310 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
311 self.paths.iter().find(|pathset| pathset.has(path))
315 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
326 impl<'a> Builder<'a> {
327 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
328 macro_rules! describe {
329 ($($rule:ty),+ $(,)*) => {{
330 vec![$(StepDescription::from::<$rule>()),+]
334 Kind::Build => describe!(
338 compile::CodegenBackend,
339 compile::StartupObjects,
343 tool::UnstableBookGen,
348 tool::RemoteTestServer,
349 tool::RemoteTestClient,
360 Kind::Check => describe!(
364 check::CodegenBackend,
367 Kind::Test => describe!(
373 test::RunPassValgrind,
380 test::RunPassFullDeps,
385 test::RunPassValgrindPretty,
395 test::RunMakeFullDeps,
406 test::CompiletestTest,
409 // Run bootstrap close to the end as it's unlikely to fail
411 // Run run-make last, since these won't pass without make on Windows
415 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
416 Kind::Doc => describe!(
418 doc::UnstableBookGen,
423 doc::WhitelistedRustc,
436 Kind::Dist => describe!(
441 dist::DebuggerScripts,
445 dist::PlainSourceTarball,
456 Kind::Install => describe!(
471 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
472 let kind = match subcommand {
473 "build" => Kind::Build,
475 "test" => Kind::Test,
476 "bench" => Kind::Bench,
477 "dist" => Kind::Dist,
478 "install" => Kind::Install,
482 let builder = Builder {
484 top_stage: build.config.stage.unwrap_or(2),
487 stack: RefCell::new(Vec::new()),
488 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
490 graph_nodes: RefCell::new(HashMap::new()),
491 graph: RefCell::new(Graph::new()),
492 parent: Cell::new(None),
495 let builder = &builder;
496 let mut should_run = ShouldRun::new(builder);
497 for desc in Builder::get_step_descriptions(builder.kind) {
498 should_run = (desc.should_run)(should_run);
500 let mut help = String::from("Available paths:\n");
501 for pathset in should_run.paths {
502 if let PathSet::Set(set) = pathset {
503 set.iter().for_each(|path| {
505 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
513 pub fn new(build: &Build) -> Builder {
514 let (kind, paths) = match build.config.cmd {
515 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
516 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
517 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
518 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
519 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
520 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
521 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
522 Subcommand::Clean { .. } => panic!(),
525 let builder = Builder {
527 top_stage: build.config.stage.unwrap_or(2),
530 stack: RefCell::new(Vec::new()),
531 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
532 paths: paths.to_owned(),
533 graph_nodes: RefCell::new(HashMap::new()),
534 graph: RefCell::new(Graph::new()),
535 parent: Cell::new(None),
538 if kind == Kind::Dist {
540 !builder.config.test_miri,
541 "Do not distribute with miri enabled.\n\
542 The distributed libraries would include all MIR (increasing binary size).
543 The distributed MIR would include validation statements."
550 pub fn execute_cli(&self) -> Graph<String, bool> {
551 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
552 self.graph.borrow().clone()
555 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
556 let paths = paths.unwrap_or(&[]);
557 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
560 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
561 StepDescription::run(v, self, paths);
564 /// Obtain a compiler at a given stage and for a given host. Explicitly does
565 /// not take `Compiler` since all `Compiler` instances are meant to be
566 /// obtained through this function, since it ensures that they are valid
567 /// (i.e., built and assembled).
568 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
569 self.ensure(compile::Assemble {
570 target_compiler: Compiler { stage, host },
574 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
575 self.ensure(compile::Sysroot { compiler })
578 /// Returns the libdir where the standard library and other artifacts are
579 /// found for a compiler's sysroot.
580 pub fn sysroot_libdir(
583 target: Interned<String>,
584 ) -> Interned<PathBuf> {
585 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
588 target: Interned<String>,
590 impl Step for Libdir {
591 type Output = Interned<PathBuf>;
593 fn should_run(run: ShouldRun) -> ShouldRun {
597 fn run(self, builder: &Builder) -> Interned<PathBuf> {
598 let compiler = self.compiler;
599 let config = &builder.build.config;
600 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
601 builder.build.config.libdir_relative().unwrap()
605 let sysroot = builder
606 .sysroot(self.compiler)
611 let _ = fs::remove_dir_all(&sysroot);
612 t!(fs::create_dir_all(&sysroot));
613 INTERNER.intern_path(sysroot)
616 self.ensure(Libdir { compiler, target })
619 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
620 self.sysroot_libdir(compiler, compiler.host)
621 .with_file_name(self.config.rust_codegen_backends_dir.clone())
624 /// Returns the compiler's libdir where it stores the dynamic libraries that
625 /// it itself links against.
627 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
629 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
630 if compiler.is_snapshot(self) {
631 self.rustc_snapshot_libdir()
633 self.sysroot(compiler).join(libdir(&compiler.host))
637 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
638 /// library lookup path.
639 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
640 // Windows doesn't need dylib path munging because the dlls for the
641 // compiler live next to the compiler and the system will find them
647 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
650 /// Get a path to the compiler specified.
651 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
652 if compiler.is_snapshot(self) {
653 self.initial_rustc.clone()
655 self.sysroot(compiler)
657 .join(exe("rustc", &compiler.host))
661 /// Get the paths to all of the compiler's codegen backends.
662 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
663 fs::read_dir(self.sysroot_codegen_backends(compiler))
666 .filter_map(Result::ok)
667 .map(|entry| entry.path())
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");
688 // Remove make-related flags that can cause jobserver problems.
689 cmd.env_remove("MAKEFLAGS");
690 cmd.env_remove("MFLAGS");
692 if let Some(linker) = self.linker(host) {
693 cmd.env("RUSTC_TARGET_LINKER", linker);
698 /// Prepares an invocation of `cargo` to be run.
700 /// This will create a `Command` that represents a pending execution of
701 /// Cargo. This cargo will be configured to use `compiler` as the actual
702 /// rustc compiler, its output will be scoped by `mode`'s output directory,
703 /// it will pass the `--target` flag for the specified `target`, and will be
704 /// executing the Cargo command `cmd`.
709 target: Interned<String>,
712 let mut cargo = Command::new(&self.initial_cargo);
713 let out_dir = self.stage_out(compiler, mode);
715 // command specific path, we call clear_if_dirty with this
716 let mut my_out = match cmd {
717 "build" => self.cargo_out(compiler, mode, target),
719 // This is the intended out directory for crate documentation.
720 "doc" | "rustdoc" => self.crate_doc_out(target),
722 _ => self.stage_out(compiler, mode),
725 // This is for the original compiler, but if we're forced to use stage 1, then
726 // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
727 // we copy the libs forward.
728 let cmp = if self.force_use_stage1(compiler, target) {
729 self.compiler(1, compiler.host)
734 let libstd_stamp = match cmd {
735 "check" => check::libstd_stamp(self, cmp, target),
736 _ => compile::libstd_stamp(self, cmp, target),
739 let libtest_stamp = match cmd {
740 "check" => check::libtest_stamp(self, cmp, target),
741 _ => compile::libstd_stamp(self, cmp, target),
744 let librustc_stamp = match cmd {
745 "check" => check::librustc_stamp(self, cmp, target),
746 _ => compile::librustc_stamp(self, cmp, target),
749 if cmd == "doc" || cmd == "rustdoc" {
750 if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
751 // This is the intended out directory for compiler documentation.
752 my_out = self.compiler_doc_out(target);
754 let rustdoc = self.rustdoc(compiler.host);
755 self.clear_if_dirty(&my_out, &rustdoc);
756 } else if cmd != "test" {
759 self.clear_if_dirty(&my_out, &self.rustc(compiler));
760 for backend in self.codegen_backends(compiler) {
761 self.clear_if_dirty(&my_out, &backend);
765 self.clear_if_dirty(&my_out, &libstd_stamp);
768 self.clear_if_dirty(&my_out, &self.rustc(compiler));
769 self.clear_if_dirty(&my_out, &libstd_stamp);
770 self.clear_if_dirty(&my_out, &libtest_stamp);
773 self.clear_if_dirty(&my_out, &librustc_stamp);
775 Mode::ToolBootstrap => { },
777 self.clear_if_dirty(&my_out, &libstd_stamp);
780 self.clear_if_dirty(&my_out, &libstd_stamp);
781 self.clear_if_dirty(&my_out, &libtest_stamp);
784 self.clear_if_dirty(&my_out, &libstd_stamp);
785 self.clear_if_dirty(&my_out, &libtest_stamp);
786 self.clear_if_dirty(&my_out, &librustc_stamp);
792 .env("CARGO_TARGET_DIR", out_dir)
795 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
796 // needs to not accidentally link to libLLVM in stage0/lib.
797 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
798 if let Some(e) = env::var_os(util::dylib_path_var()) {
799 cargo.env("REAL_LIBRARY_PATH", e);
802 if cmd != "install" {
803 cargo.arg("--target")
806 assert_eq!(target, compiler.host);
809 // Set a flag for `check` so that certain build scripts can do less work
810 // (e.g., not building/requiring LLVM).
812 cargo.env("RUST_CHECK", "1");
815 cargo.arg("-j").arg(self.jobs().to_string());
816 // Remove make-related flags to ensure Cargo can correctly set things up
817 cargo.env_remove("MAKEFLAGS");
818 cargo.env_remove("MFLAGS");
820 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
821 // Force cargo to output binaries with disambiguating hashes in the name
822 let metadata = if compiler.stage == 0 {
823 // Treat stage0 like special channel, whether it's a normal prior-
824 // release rustc or a local rebuild with the same version, so we
825 // never mix these libraries by accident.
830 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
833 if compiler.stage == 0 && self.local_rebuild {
834 // Assume the local-rebuild rustc already has stage1 features.
837 stage = compiler.stage;
840 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
842 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
843 if !extra_args.is_empty() {
844 extra_args.push_str(" ");
846 extra_args.push_str(&s);
849 if !extra_args.is_empty() {
854 env::var("RUSTFLAGS").unwrap_or_default(),
860 let want_rustdoc = self.doc_tests != DocTests::No;
862 // We synthetically interpret a stage0 compiler used to build tools as a
863 // "raw" compiler in that it's the exact snapshot we download. Normally
864 // the stage0 build means it uses libraries build by the stage0
865 // compiler, but for tools we just use the precompiled libraries that
867 let use_snapshot = mode == Mode::ToolBootstrap;
868 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
870 let maybe_sysroot = self.sysroot(compiler);
871 let sysroot = if use_snapshot {
872 self.rustc_snapshot_sysroot()
876 let libdir = sysroot.join(libdir(&compiler.host));
878 // Customize the compiler we're running. Specify the compiler to cargo
879 // as our shim and then pass it some various options used to configure
880 // how the actual compiler itself is called.
882 // These variables are primarily all read by
883 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
885 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
886 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
887 .env("RUSTC_REAL", self.rustc(compiler))
888 .env("RUSTC_STAGE", stage.to_string())
890 "RUSTC_DEBUG_ASSERTIONS",
891 self.config.rust_debug_assertions.to_string(),
893 .env("RUSTC_SYSROOT", &sysroot)
894 .env("RUSTC_LIBDIR", &libdir)
895 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
896 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
899 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
900 self.rustdoc(compiler.host)
902 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
905 .env("TEST_MIRI", self.config.test_miri.to_string())
906 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
908 if let Some(host_linker) = self.linker(compiler.host) {
909 cargo.env("RUSTC_HOST_LINKER", host_linker);
911 if let Some(target_linker) = self.linker(target) {
912 cargo.env("RUSTC_TARGET_LINKER", target_linker);
914 if let Some(ref error_format) = self.config.rustc_error_format {
915 cargo.env("RUSTC_ERROR_FORMAT", error_format);
917 if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
918 cargo.env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.config.build));
922 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
923 // enabled in the config. Adding debuginfo makes them several times larger.
924 if self.config.rust_debuginfo_tools {
925 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
927 "RUSTC_DEBUGINFO_LINES",
928 self.config.rust_debuginfo_lines.to_string(),
932 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
934 "RUSTC_DEBUGINFO_LINES",
935 self.config.rust_debuginfo_lines.to_string(),
937 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
939 // Currently the compiler depends on crates from crates.io, and
940 // then other crates can depend on the compiler (e.g., proc-macro
941 // crates). Let's say, for example that rustc itself depends on the
942 // bitflags crate. If an external crate then depends on the
943 // bitflags crate as well, we need to make sure they don't
944 // conflict, even if they pick the same version of bitflags. We'll
945 // want to make sure that e.g., a plugin and rustc each get their
946 // own copy of bitflags.
948 // Cargo ensures that this works in general through the -C metadata
949 // flag. This flag will frob the symbols in the binary to make sure
950 // they're different, even though the source code is the exact
951 // same. To solve this problem for the compiler we extend Cargo's
952 // already-passed -C metadata flag with our own. Our rustc.rs
953 // wrapper around the actual rustc will detect -C metadata being
954 // passed and frob it with this extra string we're passing in.
955 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
958 if let Some(x) = self.crt_static(target) {
959 cargo.env("RUSTC_CRT_STATIC", x.to_string());
962 if let Some(x) = self.crt_static(compiler.host) {
963 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
966 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
967 cargo.env("RUSTC_DEBUGINFO_MAP", map);
970 // Enable usage of unstable features
971 cargo.env("RUSTC_BOOTSTRAP", "1");
972 self.add_rust_test_threads(&mut cargo);
974 // Almost all of the crates that we compile as part of the bootstrap may
975 // have a build script, including the standard library. To compile a
976 // build script, however, it itself needs a standard library! This
977 // introduces a bit of a pickle when we're compiling the standard
980 // To work around this we actually end up using the snapshot compiler
981 // (stage0) for compiling build scripts of the standard library itself.
982 // The stage0 compiler is guaranteed to have a libstd available for use.
984 // For other crates, however, we know that we've already got a standard
985 // library up and running, so we can use the normal compiler to compile
986 // build scripts in that situation.
988 // If LLVM support is disabled we need to use the snapshot compiler to compile
989 // build scripts, as the new compiler doesn't support executables.
990 if mode == Mode::Std || !self.config.llvm_enabled {
992 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
993 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
996 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
997 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1000 if self.config.incremental {
1001 cargo.env("CARGO_INCREMENTAL", "1");
1003 // Don't rely on any default setting for incr. comp. in Cargo
1004 cargo.env("CARGO_INCREMENTAL", "0");
1007 if let Some(ref on_fail) = self.config.on_fail {
1008 cargo.env("RUSTC_ON_FAIL", on_fail);
1011 if self.config.print_step_timings {
1012 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1015 if self.config.backtrace_on_ice {
1016 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1019 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1021 if self.config.deny_warnings {
1022 cargo.env("RUSTC_DENY_WARNINGS", "1");
1025 // Throughout the build Cargo can execute a number of build scripts
1026 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1027 // obtained previously to those build scripts.
1028 // Build scripts use either the `cc` crate or `configure/make` so we pass
1029 // the options through environment variables that are fetched and understood by both.
1031 // FIXME: the guard against msvc shouldn't need to be here
1032 if target.contains("msvc") {
1033 if let Some(ref cl) = self.config.llvm_clang_cl {
1034 cargo.env("CC", cl).env("CXX", cl);
1037 let ccache = self.config.ccache.as_ref();
1038 let ccacheify = |s: &Path| {
1039 let ccache = match ccache {
1041 None => return s.display().to_string(),
1043 // FIXME: the cc-rs crate only recognizes the literal strings
1044 // `ccache` and `sccache` when doing caching compilations, so we
1045 // mirror that here. It should probably be fixed upstream to
1046 // accept a new env var or otherwise work with custom ccache
1049 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1050 _ => s.display().to_string(),
1053 let cc = ccacheify(&self.cc(target));
1054 cargo.env(format!("CC_{}", target), &cc);
1056 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1058 .env(format!("CFLAGS_{}", target), cflags.clone());
1060 if let Some(ar) = self.ar(target) {
1061 let ranlib = format!("{} s", ar.display());
1063 .env(format!("AR_{}", target), ar)
1064 .env(format!("RANLIB_{}", target), ranlib);
1067 if let Ok(cxx) = self.cxx(target) {
1068 let cxx = ccacheify(&cxx);
1070 .env(format!("CXX_{}", target), &cxx)
1071 .env(format!("CXXFLAGS_{}", target), cflags);
1075 if (cmd == "build" || cmd == "rustc")
1076 && mode == Mode::Std
1077 && self.config.extended
1078 && compiler.is_final_stage(self)
1080 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1083 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1084 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1086 // Environment variables *required* throughout the build
1088 // FIXME: should update code to not require this env var
1089 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1091 // Set this for all builds to make sure doc builds also get it.
1092 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1094 // This one's a bit tricky. As of the time of this writing the compiler
1095 // links to the `winapi` crate on crates.io. This crate provides raw
1096 // bindings to Windows system functions, sort of like libc does for
1097 // Unix. This crate also, however, provides "import libraries" for the
1098 // MinGW targets. There's an import library per dll in the windows
1099 // distribution which is what's linked to. These custom import libraries
1100 // are used because the winapi crate can reference Windows functions not
1101 // present in the MinGW import libraries.
1103 // For example MinGW may ship libdbghelp.a, but it may not have
1104 // references to all the functions in the dbghelp dll. Instead the
1105 // custom import library for dbghelp in the winapi crates has all this
1108 // Unfortunately for us though the import libraries are linked by
1109 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1110 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1111 // conflict with the system MinGW ones). This consequently means that
1112 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1113 // DLL) when linked against *again*, for example with procedural macros
1114 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1115 // `-lwinapi_foo` to the linker again. This isn't actually available in
1116 // our distribution, however, so the link fails.
1118 // To solve this problem we tell winapi to not use its bundled import
1119 // libraries. This means that it will link to the system MinGW import
1120 // libraries by default, and the `-ldylib=foo` directives will still get
1121 // passed to the final linker, but they'll look like `-lfoo` which can
1122 // be resolved because MinGW has the import library. The downside is we
1123 // don't get newer functions from Windows, but we don't use any of them
1125 if !mode.is_tool() {
1126 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1129 for _ in 1..self.verbosity {
1133 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1134 (Mode::Std, Some(n), _) |
1135 (Mode::Test, Some(n), _) |
1136 (_, _, Some(n)) => {
1137 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1140 // Don't set anything
1144 if self.config.rust_optimize {
1145 // FIXME: cargo bench/install do not accept `--release`
1146 if cmd != "bench" && cmd != "install" {
1147 cargo.arg("--release");
1151 if self.config.locked_deps {
1152 cargo.arg("--locked");
1154 if self.config.vendor || self.is_sudo {
1155 cargo.arg("--frozen");
1158 self.ci_env.force_coloring_in_ci(&mut cargo);
1163 /// Ensure that a given step is built, returning its output. This will
1164 /// cache the step, so it is safe (and good!) to call this as often as
1165 /// needed to ensure that all dependencies are built.
1166 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1168 let mut stack = self.stack.borrow_mut();
1169 for stack_step in stack.iter() {
1172 .downcast_ref::<S>()
1173 .map_or(true, |stack_step| *stack_step != step)
1177 let mut out = String::new();
1178 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1179 for el in stack.iter().rev() {
1180 out += &format!("\t{:?}\n", el);
1184 if let Some(out) = self.cache.get(&step) {
1185 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1188 let mut graph = self.graph.borrow_mut();
1189 let parent = self.parent.get();
1193 .entry(format!("{:?}", step))
1194 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1195 if let Some(parent) = parent {
1196 graph.add_edge(parent, us, false);
1202 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1203 stack.push(Box::new(step.clone()));
1206 let prev_parent = self.parent.get();
1209 let mut graph = self.graph.borrow_mut();
1210 let parent = self.parent.get();
1214 .entry(format!("{:?}", step))
1215 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1216 self.parent.set(Some(us));
1217 if let Some(parent) = parent {
1218 graph.add_edge(parent, us, true);
1223 let start = Instant::now();
1224 let zero = Duration::new(0, 0);
1225 let parent = self.time_spent_on_dependencies.replace(zero);
1226 let out = step.clone().run(self);
1227 let dur = start.elapsed();
1228 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1232 self.parent.set(prev_parent);
1234 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1236 "[TIMING] {:?} -- {}.{:03}",
1239 dur.subsec_nanos() / 1_000_000
1244 let mut stack = self.stack.borrow_mut();
1245 let cur_step = stack.pop().expect("step stack empty");
1246 assert_eq!(cur_step.downcast_ref(), Some(&step));
1248 self.verbose(&format!(
1250 " ".repeat(self.stack.borrow().len()),
1253 self.cache.put(step, out.clone());
1261 use crate::config::Config;
1264 fn configure(host: &[&str], target: &[&str]) -> Config {
1265 let mut config = Config::default_opts();
1266 // don't save toolstates
1267 config.save_toolstates = None;
1268 config.run_host_only = true;
1269 config.dry_run = true;
1270 // try to avoid spurious failures in dist where we create/delete each others file
1271 let dir = config.out.join("tmp-rustbuild-tests").join(
1274 .unwrap_or("unknown")
1277 t!(fs::create_dir_all(&dir));
1279 config.build = INTERNER.intern_str("A");
1280 config.hosts = vec![config.build]
1283 .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1284 .collect::<Vec<_>>();
1285 config.targets = config
1289 .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1290 .collect::<Vec<_>>();
1294 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1295 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1299 fn dist_baseline() {
1300 let build = Build::new(configure(&[], &[]));
1301 let mut builder = Builder::new(&build);
1302 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1304 let a = INTERNER.intern_str("A");
1307 first(builder.cache.all::<dist::Docs>()),
1308 &[dist::Docs { stage: 2, host: a },]
1311 first(builder.cache.all::<dist::Mingw>()),
1312 &[dist::Mingw { host: a },]
1315 first(builder.cache.all::<dist::Rustc>()),
1317 compiler: Compiler { host: a, stage: 2 }
1321 first(builder.cache.all::<dist::Std>()),
1323 compiler: Compiler { host: a, stage: 2 },
1327 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1331 fn dist_with_targets() {
1332 let build = Build::new(configure(&[], &["B"]));
1333 let mut builder = Builder::new(&build);
1334 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1336 let a = INTERNER.intern_str("A");
1337 let b = INTERNER.intern_str("B");
1340 first(builder.cache.all::<dist::Docs>()),
1342 dist::Docs { stage: 2, host: a },
1343 dist::Docs { stage: 2, host: b },
1347 first(builder.cache.all::<dist::Mingw>()),
1348 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1351 first(builder.cache.all::<dist::Rustc>()),
1353 compiler: Compiler { host: a, stage: 2 }
1357 first(builder.cache.all::<dist::Std>()),
1360 compiler: Compiler { host: a, stage: 2 },
1364 compiler: Compiler { host: a, stage: 2 },
1369 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1373 fn dist_with_hosts() {
1374 let build = Build::new(configure(&["B"], &[]));
1375 let mut builder = Builder::new(&build);
1376 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1378 let a = INTERNER.intern_str("A");
1379 let b = INTERNER.intern_str("B");
1382 first(builder.cache.all::<dist::Docs>()),
1384 dist::Docs { stage: 2, host: a },
1385 dist::Docs { stage: 2, host: b },
1389 first(builder.cache.all::<dist::Mingw>()),
1390 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1393 first(builder.cache.all::<dist::Rustc>()),
1396 compiler: Compiler { host: a, stage: 2 }
1399 compiler: Compiler { host: b, stage: 2 }
1404 first(builder.cache.all::<dist::Std>()),
1407 compiler: Compiler { host: a, stage: 2 },
1411 compiler: Compiler { host: a, stage: 2 },
1416 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1420 fn dist_with_targets_and_hosts() {
1421 let build = Build::new(configure(&["B"], &["C"]));
1422 let mut builder = Builder::new(&build);
1423 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1425 let a = INTERNER.intern_str("A");
1426 let b = INTERNER.intern_str("B");
1427 let c = INTERNER.intern_str("C");
1430 first(builder.cache.all::<dist::Docs>()),
1432 dist::Docs { stage: 2, host: a },
1433 dist::Docs { stage: 2, host: b },
1434 dist::Docs { stage: 2, host: c },
1438 first(builder.cache.all::<dist::Mingw>()),
1440 dist::Mingw { host: a },
1441 dist::Mingw { host: b },
1442 dist::Mingw { host: c },
1446 first(builder.cache.all::<dist::Rustc>()),
1449 compiler: Compiler { host: a, stage: 2 }
1452 compiler: Compiler { host: b, stage: 2 }
1457 first(builder.cache.all::<dist::Std>()),
1460 compiler: Compiler { host: a, stage: 2 },
1464 compiler: Compiler { host: a, stage: 2 },
1468 compiler: Compiler { host: a, stage: 2 },
1473 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1477 fn dist_with_target_flag() {
1478 let mut config = configure(&["B"], &["C"]);
1479 config.run_host_only = false; // as-if --target=C was passed
1480 let build = Build::new(config);
1481 let mut builder = Builder::new(&build);
1482 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1484 let a = INTERNER.intern_str("A");
1485 let b = INTERNER.intern_str("B");
1486 let c = INTERNER.intern_str("C");
1489 first(builder.cache.all::<dist::Docs>()),
1491 dist::Docs { stage: 2, host: a },
1492 dist::Docs { stage: 2, host: b },
1493 dist::Docs { stage: 2, host: c },
1497 first(builder.cache.all::<dist::Mingw>()),
1499 dist::Mingw { host: a },
1500 dist::Mingw { host: b },
1501 dist::Mingw { host: c },
1504 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1506 first(builder.cache.all::<dist::Std>()),
1509 compiler: Compiler { host: a, stage: 2 },
1513 compiler: Compiler { host: a, stage: 2 },
1517 compiler: Compiler { host: a, stage: 2 },
1522 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1526 fn dist_with_same_targets_and_hosts() {
1527 let build = Build::new(configure(&["B"], &["B"]));
1528 let mut builder = Builder::new(&build);
1529 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1531 let a = INTERNER.intern_str("A");
1532 let b = INTERNER.intern_str("B");
1535 first(builder.cache.all::<dist::Docs>()),
1537 dist::Docs { stage: 2, host: a },
1538 dist::Docs { stage: 2, host: b },
1542 first(builder.cache.all::<dist::Mingw>()),
1543 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1546 first(builder.cache.all::<dist::Rustc>()),
1549 compiler: Compiler { host: a, stage: 2 }
1552 compiler: Compiler { host: b, stage: 2 }
1557 first(builder.cache.all::<dist::Std>()),
1560 compiler: Compiler { host: a, stage: 2 },
1564 compiler: Compiler { host: a, stage: 2 },
1569 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1571 first(builder.cache.all::<compile::Std>()),
1574 compiler: Compiler { host: a, stage: 0 },
1578 compiler: Compiler { host: a, stage: 1 },
1582 compiler: Compiler { host: a, stage: 2 },
1586 compiler: Compiler { host: a, stage: 1 },
1590 compiler: Compiler { host: a, stage: 2 },
1596 first(builder.cache.all::<compile::Test>()),
1599 compiler: Compiler { host: a, stage: 0 },
1603 compiler: Compiler { host: a, stage: 1 },
1607 compiler: Compiler { host: a, stage: 2 },
1611 compiler: Compiler { host: a, stage: 1 },
1615 compiler: Compiler { host: a, stage: 2 },
1621 first(builder.cache.all::<compile::Assemble>()),
1624 target_compiler: Compiler { host: a, stage: 0 },
1627 target_compiler: Compiler { host: a, stage: 1 },
1630 target_compiler: Compiler { host: a, stage: 2 },
1633 target_compiler: Compiler { host: b, stage: 2 },
1640 fn build_default() {
1641 let build = Build::new(configure(&["B"], &["C"]));
1642 let mut builder = Builder::new(&build);
1643 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1645 let a = INTERNER.intern_str("A");
1646 let b = INTERNER.intern_str("B");
1647 let c = INTERNER.intern_str("C");
1649 assert!(!builder.cache.all::<compile::Std>().is_empty());
1650 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1652 first(builder.cache.all::<compile::Rustc>()),
1655 compiler: Compiler { host: a, stage: 0 },
1659 compiler: Compiler { host: a, stage: 1 },
1663 compiler: Compiler { host: a, stage: 2 },
1667 compiler: Compiler { host: b, stage: 2 },
1671 compiler: Compiler { host: a, stage: 0 },
1675 compiler: Compiler { host: a, stage: 1 },
1679 compiler: Compiler { host: a, stage: 2 },
1683 compiler: Compiler { host: b, stage: 2 },
1690 first(builder.cache.all::<compile::Test>()),
1693 compiler: Compiler { host: a, stage: 0 },
1697 compiler: Compiler { host: a, stage: 1 },
1701 compiler: Compiler { host: a, stage: 2 },
1705 compiler: Compiler { host: b, stage: 2 },
1709 compiler: Compiler { host: a, stage: 0 },
1713 compiler: Compiler { host: a, stage: 1 },
1717 compiler: Compiler { host: a, stage: 2 },
1721 compiler: Compiler { host: b, stage: 2 },
1725 compiler: Compiler { host: a, stage: 2 },
1729 compiler: Compiler { host: b, stage: 2 },
1737 fn build_with_target_flag() {
1738 let mut config = configure(&["B"], &["C"]);
1739 config.run_host_only = false;
1740 let build = Build::new(config);
1741 let mut builder = Builder::new(&build);
1742 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1744 let a = INTERNER.intern_str("A");
1745 let b = INTERNER.intern_str("B");
1746 let c = INTERNER.intern_str("C");
1748 assert!(!builder.cache.all::<compile::Std>().is_empty());
1750 first(builder.cache.all::<compile::Assemble>()),
1753 target_compiler: Compiler { host: a, stage: 0 },
1756 target_compiler: Compiler { host: a, stage: 1 },
1759 target_compiler: Compiler { host: b, stage: 1 },
1762 target_compiler: Compiler { host: a, stage: 2 },
1765 target_compiler: Compiler { host: b, stage: 2 },
1770 first(builder.cache.all::<compile::Rustc>()),
1773 compiler: Compiler { host: a, stage: 0 },
1777 compiler: Compiler { host: a, stage: 1 },
1781 compiler: Compiler { host: a, stage: 0 },
1785 compiler: Compiler { host: a, stage: 1 },
1792 first(builder.cache.all::<compile::Test>()),
1795 compiler: Compiler { host: a, stage: 0 },
1799 compiler: Compiler { host: a, stage: 1 },
1803 compiler: Compiler { host: a, stage: 2 },
1807 compiler: Compiler { host: b, stage: 2 },
1811 compiler: Compiler { host: a, stage: 0 },
1815 compiler: Compiler { host: a, stage: 1 },
1819 compiler: Compiler { host: a, stage: 2 },
1823 compiler: Compiler { host: b, stage: 2 },
1827 compiler: Compiler { host: a, stage: 2 },
1831 compiler: Compiler { host: b, stage: 2 },
1839 fn test_with_no_doc_stage0() {
1840 let mut config = configure(&[], &[]);
1841 config.stage = Some(0);
1842 config.cmd = Subcommand::Test {
1843 paths: vec!["src/libstd".into()],
1847 doc_tests: DocTests::No,
1852 let build = Build::new(config);
1853 let mut builder = Builder::new(&build);
1855 let host = INTERNER.intern_str("A");
1857 builder.run_step_descriptions(
1858 &[StepDescription::from::<test::Crate>()],
1859 &["src/libstd".into()],
1862 // Ensure we don't build any compiler artifacts.
1863 assert!(!builder.cache.contains::<compile::Rustc>());
1865 first(builder.cache.all::<test::Crate>()),
1867 compiler: Compiler { host, stage: 0 },
1870 test_kind: test::TestKind::Test,
1871 krate: INTERNER.intern_str("std"),
1878 let mut config = configure(&[], &[]);
1879 config.exclude = vec![
1880 "src/test/run-pass".into(),
1881 "src/tools/tidy".into(),
1883 config.cmd = Subcommand::Test {
1885 test_args: Vec::new(),
1886 rustc_args: Vec::new(),
1888 doc_tests: DocTests::No,
1893 let build = Build::new(config);
1894 let builder = Builder::new(&build);
1895 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1897 // Ensure we have really excluded run-pass & tidy
1898 assert!(!builder.cache.contains::<test::RunPass>());
1899 assert!(!builder.cache.contains::<test::Tidy>());
1901 // Ensure other tests are not affected.
1902 assert!(builder.cache.contains::<test::RunPassFullDeps>());
1903 assert!(builder.cache.contains::<test::RustdocUi>());