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,
407 test::CompiletestTest,
410 // Run bootstrap close to the end as it's unlikely to fail
412 // Run run-make last, since these won't pass without make on Windows
416 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
417 Kind::Doc => describe!(
419 doc::UnstableBookGen,
424 doc::WhitelistedRustc,
437 Kind::Dist => describe!(
442 dist::DebuggerScripts,
446 dist::PlainSourceTarball,
457 Kind::Install => describe!(
472 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
473 let kind = match subcommand {
474 "build" => Kind::Build,
476 "test" => Kind::Test,
477 "bench" => Kind::Bench,
478 "dist" => Kind::Dist,
479 "install" => Kind::Install,
483 let builder = Builder {
485 top_stage: build.config.stage.unwrap_or(2),
488 stack: RefCell::new(Vec::new()),
489 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
491 graph_nodes: RefCell::new(HashMap::new()),
492 graph: RefCell::new(Graph::new()),
493 parent: Cell::new(None),
496 let builder = &builder;
497 let mut should_run = ShouldRun::new(builder);
498 for desc in Builder::get_step_descriptions(builder.kind) {
499 should_run = (desc.should_run)(should_run);
501 let mut help = String::from("Available paths:\n");
502 for pathset in should_run.paths {
503 if let PathSet::Set(set) = pathset {
504 set.iter().for_each(|path| {
506 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
514 pub fn new(build: &Build) -> Builder {
515 let (kind, paths) = match build.config.cmd {
516 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
517 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
518 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
519 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
520 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
521 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
522 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
523 Subcommand::Clean { .. } => panic!(),
526 let builder = Builder {
528 top_stage: build.config.stage.unwrap_or(2),
531 stack: RefCell::new(Vec::new()),
532 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
533 paths: paths.to_owned(),
534 graph_nodes: RefCell::new(HashMap::new()),
535 graph: RefCell::new(Graph::new()),
536 parent: Cell::new(None),
539 if kind == Kind::Dist {
541 !builder.config.test_miri,
542 "Do not distribute with miri enabled.\n\
543 The distributed libraries would include all MIR (increasing binary size).
544 The distributed MIR would include validation statements."
551 pub fn execute_cli(&self) -> Graph<String, bool> {
552 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
553 self.graph.borrow().clone()
556 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
557 let paths = paths.unwrap_or(&[]);
558 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
561 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
562 StepDescription::run(v, self, paths);
565 /// Obtain a compiler at a given stage and for a given host. Explicitly does
566 /// not take `Compiler` since all `Compiler` instances are meant to be
567 /// obtained through this function, since it ensures that they are valid
568 /// (i.e., built and assembled).
569 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
570 self.ensure(compile::Assemble {
571 target_compiler: Compiler { stage, host },
575 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
576 self.ensure(compile::Sysroot { compiler })
579 /// Returns the libdir where the standard library and other artifacts are
580 /// found for a compiler's sysroot.
581 pub fn sysroot_libdir(
584 target: Interned<String>,
585 ) -> Interned<PathBuf> {
586 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
589 target: Interned<String>,
591 impl Step for Libdir {
592 type Output = Interned<PathBuf>;
594 fn should_run(run: ShouldRun) -> ShouldRun {
598 fn run(self, builder: &Builder) -> Interned<PathBuf> {
599 let compiler = self.compiler;
600 let config = &builder.build.config;
601 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
602 builder.build.config.libdir_relative().unwrap()
606 let sysroot = builder
607 .sysroot(self.compiler)
612 let _ = fs::remove_dir_all(&sysroot);
613 t!(fs::create_dir_all(&sysroot));
614 INTERNER.intern_path(sysroot)
617 self.ensure(Libdir { compiler, target })
620 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
621 self.sysroot_libdir(compiler, compiler.host)
622 .with_file_name(self.config.rust_codegen_backends_dir.clone())
625 /// Returns the compiler's libdir where it stores the dynamic libraries that
626 /// it itself links against.
628 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
630 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
631 if compiler.is_snapshot(self) {
632 self.rustc_snapshot_libdir()
634 self.sysroot(compiler).join(libdir(&compiler.host))
638 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
639 /// library lookup path.
640 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
641 // Windows doesn't need dylib path munging because the dlls for the
642 // compiler live next to the compiler and the system will find them
648 add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
651 /// Get a path to the compiler specified.
652 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
653 if compiler.is_snapshot(self) {
654 self.initial_rustc.clone()
656 self.sysroot(compiler)
658 .join(exe("rustc", &compiler.host))
662 /// Get the paths to all of the compiler's codegen backends.
663 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
664 fs::read_dir(self.sysroot_codegen_backends(compiler))
667 .filter_map(Result::ok)
668 .map(|entry| entry.path())
671 pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
672 self.ensure(tool::Rustdoc { host })
675 pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
676 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
677 let compiler = self.compiler(self.top_stage, host);
678 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
679 .env("RUSTC_SYSROOT", self.sysroot(compiler))
682 self.sysroot_libdir(compiler, self.config.build),
684 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
685 .env("RUSTDOC_REAL", self.rustdoc(host))
686 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
687 .env("RUSTC_BOOTSTRAP", "1");
689 // Remove make-related flags that can cause jobserver problems.
690 cmd.env_remove("MAKEFLAGS");
691 cmd.env_remove("MFLAGS");
693 if let Some(linker) = self.linker(host) {
694 cmd.env("RUSTC_TARGET_LINKER", linker);
699 /// Prepares an invocation of `cargo` to be run.
701 /// This will create a `Command` that represents a pending execution of
702 /// Cargo. This cargo will be configured to use `compiler` as the actual
703 /// rustc compiler, its output will be scoped by `mode`'s output directory,
704 /// it will pass the `--target` flag for the specified `target`, and will be
705 /// executing the Cargo command `cmd`.
710 target: Interned<String>,
713 let mut cargo = Command::new(&self.initial_cargo);
714 let out_dir = self.stage_out(compiler, mode);
716 // command specific path, we call clear_if_dirty with this
717 let mut my_out = match cmd {
718 "build" => self.cargo_out(compiler, mode, target),
720 // This is the intended out directory for crate documentation.
721 "doc" | "rustdoc" => self.crate_doc_out(target),
723 _ => self.stage_out(compiler, mode),
726 // This is for the original compiler, but if we're forced to use stage 1, then
727 // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
728 // we copy the libs forward.
729 let cmp = if self.force_use_stage1(compiler, target) {
730 self.compiler(1, compiler.host)
735 let libstd_stamp = match cmd {
736 "check" => check::libstd_stamp(self, cmp, target),
737 _ => compile::libstd_stamp(self, cmp, target),
740 let libtest_stamp = match cmd {
741 "check" => check::libtest_stamp(self, cmp, target),
742 _ => compile::libstd_stamp(self, cmp, target),
745 let librustc_stamp = match cmd {
746 "check" => check::librustc_stamp(self, cmp, target),
747 _ => compile::librustc_stamp(self, cmp, target),
750 if cmd == "doc" || cmd == "rustdoc" {
751 if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
752 // This is the intended out directory for compiler documentation.
753 my_out = self.compiler_doc_out(target);
755 let rustdoc = self.rustdoc(compiler.host);
756 self.clear_if_dirty(&my_out, &rustdoc);
757 } else if cmd != "test" {
760 self.clear_if_dirty(&my_out, &self.rustc(compiler));
761 for backend in self.codegen_backends(compiler) {
762 self.clear_if_dirty(&my_out, &backend);
766 self.clear_if_dirty(&my_out, &libstd_stamp);
769 self.clear_if_dirty(&my_out, &self.rustc(compiler));
770 self.clear_if_dirty(&my_out, &libstd_stamp);
771 self.clear_if_dirty(&my_out, &libtest_stamp);
774 self.clear_if_dirty(&my_out, &librustc_stamp);
776 Mode::ToolBootstrap => { },
778 self.clear_if_dirty(&my_out, &libstd_stamp);
781 self.clear_if_dirty(&my_out, &libstd_stamp);
782 self.clear_if_dirty(&my_out, &libtest_stamp);
785 self.clear_if_dirty(&my_out, &libstd_stamp);
786 self.clear_if_dirty(&my_out, &libtest_stamp);
787 self.clear_if_dirty(&my_out, &librustc_stamp);
793 .env("CARGO_TARGET_DIR", out_dir)
796 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
797 // needs to not accidentally link to libLLVM in stage0/lib.
798 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
799 if let Some(e) = env::var_os(util::dylib_path_var()) {
800 cargo.env("REAL_LIBRARY_PATH", e);
803 if cmd != "install" {
804 cargo.arg("--target")
807 assert_eq!(target, compiler.host);
810 // Set a flag for `check` so that certain build scripts can do less work
811 // (e.g., not building/requiring LLVM).
813 cargo.env("RUST_CHECK", "1");
816 cargo.arg("-j").arg(self.jobs().to_string());
817 // Remove make-related flags to ensure Cargo can correctly set things up
818 cargo.env_remove("MAKEFLAGS");
819 cargo.env_remove("MFLAGS");
821 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
822 // Force cargo to output binaries with disambiguating hashes in the name
823 let metadata = if compiler.stage == 0 {
824 // Treat stage0 like special channel, whether it's a normal prior-
825 // release rustc or a local rebuild with the same version, so we
826 // never mix these libraries by accident.
831 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
834 if compiler.stage == 0 && self.local_rebuild {
835 // Assume the local-rebuild rustc already has stage1 features.
838 stage = compiler.stage;
841 let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
843 let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
844 if !extra_args.is_empty() {
845 extra_args.push_str(" ");
847 extra_args.push_str(&s);
850 if !extra_args.is_empty() {
855 env::var("RUSTFLAGS").unwrap_or_default(),
861 let want_rustdoc = self.doc_tests != DocTests::No;
863 // We synthetically interpret a stage0 compiler used to build tools as a
864 // "raw" compiler in that it's the exact snapshot we download. Normally
865 // the stage0 build means it uses libraries build by the stage0
866 // compiler, but for tools we just use the precompiled libraries that
868 let use_snapshot = mode == Mode::ToolBootstrap;
869 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
871 let maybe_sysroot = self.sysroot(compiler);
872 let sysroot = if use_snapshot {
873 self.rustc_snapshot_sysroot()
877 let libdir = sysroot.join(libdir(&compiler.host));
879 // Customize the compiler we're running. Specify the compiler to cargo
880 // as our shim and then pass it some various options used to configure
881 // how the actual compiler itself is called.
883 // These variables are primarily all read by
884 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
886 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
887 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
888 .env("RUSTC_REAL", self.rustc(compiler))
889 .env("RUSTC_STAGE", stage.to_string())
891 "RUSTC_DEBUG_ASSERTIONS",
892 self.config.rust_debug_assertions.to_string(),
894 .env("RUSTC_SYSROOT", &sysroot)
895 .env("RUSTC_LIBDIR", &libdir)
896 .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
897 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
900 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
901 self.rustdoc(compiler.host)
903 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
906 .env("TEST_MIRI", self.config.test_miri.to_string())
907 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
909 if let Some(host_linker) = self.linker(compiler.host) {
910 cargo.env("RUSTC_HOST_LINKER", host_linker);
912 if let Some(target_linker) = self.linker(target) {
913 cargo.env("RUSTC_TARGET_LINKER", target_linker);
915 if let Some(ref error_format) = self.config.rustc_error_format {
916 cargo.env("RUSTC_ERROR_FORMAT", error_format);
918 if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
919 cargo.env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.config.build));
923 // Tools like cargo and rls don't get debuginfo by default right now, but this can be
924 // enabled in the config. Adding debuginfo makes them several times larger.
925 if self.config.rust_debuginfo_tools {
926 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
928 "RUSTC_DEBUGINFO_LINES",
929 self.config.rust_debuginfo_lines.to_string(),
933 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
935 "RUSTC_DEBUGINFO_LINES",
936 self.config.rust_debuginfo_lines.to_string(),
938 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
940 // Currently the compiler depends on crates from crates.io, and
941 // then other crates can depend on the compiler (e.g., proc-macro
942 // crates). Let's say, for example that rustc itself depends on the
943 // bitflags crate. If an external crate then depends on the
944 // bitflags crate as well, we need to make sure they don't
945 // conflict, even if they pick the same version of bitflags. We'll
946 // want to make sure that e.g., a plugin and rustc each get their
947 // own copy of bitflags.
949 // Cargo ensures that this works in general through the -C metadata
950 // flag. This flag will frob the symbols in the binary to make sure
951 // they're different, even though the source code is the exact
952 // same. To solve this problem for the compiler we extend Cargo's
953 // already-passed -C metadata flag with our own. Our rustc.rs
954 // wrapper around the actual rustc will detect -C metadata being
955 // passed and frob it with this extra string we're passing in.
956 cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
959 if let Some(x) = self.crt_static(target) {
960 cargo.env("RUSTC_CRT_STATIC", x.to_string());
963 if let Some(x) = self.crt_static(compiler.host) {
964 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
967 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
968 cargo.env("RUSTC_DEBUGINFO_MAP", map);
971 // Enable usage of unstable features
972 cargo.env("RUSTC_BOOTSTRAP", "1");
973 self.add_rust_test_threads(&mut cargo);
975 // Almost all of the crates that we compile as part of the bootstrap may
976 // have a build script, including the standard library. To compile a
977 // build script, however, it itself needs a standard library! This
978 // introduces a bit of a pickle when we're compiling the standard
981 // To work around this we actually end up using the snapshot compiler
982 // (stage0) for compiling build scripts of the standard library itself.
983 // The stage0 compiler is guaranteed to have a libstd available for use.
985 // For other crates, however, we know that we've already got a standard
986 // library up and running, so we can use the normal compiler to compile
987 // build scripts in that situation.
989 // If LLVM support is disabled we need to use the snapshot compiler to compile
990 // build scripts, as the new compiler doesn't support executables.
991 if mode == Mode::Std || !self.config.llvm_enabled {
993 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
994 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
997 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
998 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1001 if self.config.incremental {
1002 cargo.env("CARGO_INCREMENTAL", "1");
1004 // Don't rely on any default setting for incr. comp. in Cargo
1005 cargo.env("CARGO_INCREMENTAL", "0");
1008 if let Some(ref on_fail) = self.config.on_fail {
1009 cargo.env("RUSTC_ON_FAIL", on_fail);
1012 if self.config.print_step_timings {
1013 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1016 if self.config.backtrace_on_ice {
1017 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1020 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1022 if self.config.deny_warnings {
1023 cargo.env("RUSTC_DENY_WARNINGS", "1");
1026 // Throughout the build Cargo can execute a number of build scripts
1027 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1028 // obtained previously to those build scripts.
1029 // Build scripts use either the `cc` crate or `configure/make` so we pass
1030 // the options through environment variables that are fetched and understood by both.
1032 // FIXME: the guard against msvc shouldn't need to be here
1033 if target.contains("msvc") {
1034 if let Some(ref cl) = self.config.llvm_clang_cl {
1035 cargo.env("CC", cl).env("CXX", cl);
1038 let ccache = self.config.ccache.as_ref();
1039 let ccacheify = |s: &Path| {
1040 let ccache = match ccache {
1042 None => return s.display().to_string(),
1044 // FIXME: the cc-rs crate only recognizes the literal strings
1045 // `ccache` and `sccache` when doing caching compilations, so we
1046 // mirror that here. It should probably be fixed upstream to
1047 // accept a new env var or otherwise work with custom ccache
1050 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1051 _ => s.display().to_string(),
1054 let cc = ccacheify(&self.cc(target));
1055 cargo.env(format!("CC_{}", target), &cc);
1057 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1059 .env(format!("CFLAGS_{}", target), cflags.clone());
1061 if let Some(ar) = self.ar(target) {
1062 let ranlib = format!("{} s", ar.display());
1064 .env(format!("AR_{}", target), ar)
1065 .env(format!("RANLIB_{}", target), ranlib);
1068 if let Ok(cxx) = self.cxx(target) {
1069 let cxx = ccacheify(&cxx);
1071 .env(format!("CXX_{}", target), &cxx)
1072 .env(format!("CXXFLAGS_{}", target), cflags);
1076 if (cmd == "build" || cmd == "rustc")
1077 && mode == Mode::Std
1078 && self.config.extended
1079 && compiler.is_final_stage(self)
1081 cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1084 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1085 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1087 // Environment variables *required* throughout the build
1089 // FIXME: should update code to not require this env var
1090 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1092 // Set this for all builds to make sure doc builds also get it.
1093 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1095 // This one's a bit tricky. As of the time of this writing the compiler
1096 // links to the `winapi` crate on crates.io. This crate provides raw
1097 // bindings to Windows system functions, sort of like libc does for
1098 // Unix. This crate also, however, provides "import libraries" for the
1099 // MinGW targets. There's an import library per dll in the windows
1100 // distribution which is what's linked to. These custom import libraries
1101 // are used because the winapi crate can reference Windows functions not
1102 // present in the MinGW import libraries.
1104 // For example MinGW may ship libdbghelp.a, but it may not have
1105 // references to all the functions in the dbghelp dll. Instead the
1106 // custom import library for dbghelp in the winapi crates has all this
1109 // Unfortunately for us though the import libraries are linked by
1110 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1111 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1112 // conflict with the system MinGW ones). This consequently means that
1113 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1114 // DLL) when linked against *again*, for example with procedural macros
1115 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1116 // `-lwinapi_foo` to the linker again. This isn't actually available in
1117 // our distribution, however, so the link fails.
1119 // To solve this problem we tell winapi to not use its bundled import
1120 // libraries. This means that it will link to the system MinGW import
1121 // libraries by default, and the `-ldylib=foo` directives will still get
1122 // passed to the final linker, but they'll look like `-lfoo` which can
1123 // be resolved because MinGW has the import library. The downside is we
1124 // don't get newer functions from Windows, but we don't use any of them
1126 if !mode.is_tool() {
1127 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1130 for _ in 1..self.verbosity {
1134 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1135 (Mode::Std, Some(n), _) |
1136 (Mode::Test, Some(n), _) |
1137 (_, _, Some(n)) => {
1138 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1141 // Don't set anything
1145 if self.config.rust_optimize {
1146 // FIXME: cargo bench/install do not accept `--release`
1147 if cmd != "bench" && cmd != "install" {
1148 cargo.arg("--release");
1152 if self.config.locked_deps {
1153 cargo.arg("--locked");
1155 if self.config.vendor || self.is_sudo {
1156 cargo.arg("--frozen");
1159 self.ci_env.force_coloring_in_ci(&mut cargo);
1164 /// Ensure that a given step is built, returning its output. This will
1165 /// cache the step, so it is safe (and good!) to call this as often as
1166 /// needed to ensure that all dependencies are built.
1167 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1169 let mut stack = self.stack.borrow_mut();
1170 for stack_step in stack.iter() {
1173 .downcast_ref::<S>()
1174 .map_or(true, |stack_step| *stack_step != step)
1178 let mut out = String::new();
1179 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1180 for el in stack.iter().rev() {
1181 out += &format!("\t{:?}\n", el);
1185 if let Some(out) = self.cache.get(&step) {
1186 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1189 let mut graph = self.graph.borrow_mut();
1190 let parent = self.parent.get();
1194 .entry(format!("{:?}", step))
1195 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1196 if let Some(parent) = parent {
1197 graph.add_edge(parent, us, false);
1203 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1204 stack.push(Box::new(step.clone()));
1207 let prev_parent = self.parent.get();
1210 let mut graph = self.graph.borrow_mut();
1211 let parent = self.parent.get();
1215 .entry(format!("{:?}", step))
1216 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1217 self.parent.set(Some(us));
1218 if let Some(parent) = parent {
1219 graph.add_edge(parent, us, true);
1224 let start = Instant::now();
1225 let zero = Duration::new(0, 0);
1226 let parent = self.time_spent_on_dependencies.replace(zero);
1227 let out = step.clone().run(self);
1228 let dur = start.elapsed();
1229 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1233 self.parent.set(prev_parent);
1235 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1237 "[TIMING] {:?} -- {}.{:03}",
1240 dur.subsec_nanos() / 1_000_000
1245 let mut stack = self.stack.borrow_mut();
1246 let cur_step = stack.pop().expect("step stack empty");
1247 assert_eq!(cur_step.downcast_ref(), Some(&step));
1249 self.verbose(&format!(
1251 " ".repeat(self.stack.borrow().len()),
1254 self.cache.put(step, out.clone());
1262 use crate::config::Config;
1265 fn configure(host: &[&str], target: &[&str]) -> Config {
1266 let mut config = Config::default_opts();
1267 // don't save toolstates
1268 config.save_toolstates = None;
1269 config.run_host_only = true;
1270 config.dry_run = true;
1271 // try to avoid spurious failures in dist where we create/delete each others file
1272 let dir = config.out.join("tmp-rustbuild-tests").join(
1275 .unwrap_or("unknown")
1278 t!(fs::create_dir_all(&dir));
1280 config.build = INTERNER.intern_str("A");
1281 config.hosts = vec![config.build]
1284 .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1285 .collect::<Vec<_>>();
1286 config.targets = config
1290 .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1291 .collect::<Vec<_>>();
1295 fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1296 v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1300 fn dist_baseline() {
1301 let build = Build::new(configure(&[], &[]));
1302 let mut builder = Builder::new(&build);
1303 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1305 let a = INTERNER.intern_str("A");
1308 first(builder.cache.all::<dist::Docs>()),
1309 &[dist::Docs { stage: 2, host: a },]
1312 first(builder.cache.all::<dist::Mingw>()),
1313 &[dist::Mingw { host: a },]
1316 first(builder.cache.all::<dist::Rustc>()),
1318 compiler: Compiler { host: a, stage: 2 }
1322 first(builder.cache.all::<dist::Std>()),
1324 compiler: Compiler { host: a, stage: 2 },
1328 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1332 fn dist_with_targets() {
1333 let build = Build::new(configure(&[], &["B"]));
1334 let mut builder = Builder::new(&build);
1335 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1337 let a = INTERNER.intern_str("A");
1338 let b = INTERNER.intern_str("B");
1341 first(builder.cache.all::<dist::Docs>()),
1343 dist::Docs { stage: 2, host: a },
1344 dist::Docs { stage: 2, host: b },
1348 first(builder.cache.all::<dist::Mingw>()),
1349 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1352 first(builder.cache.all::<dist::Rustc>()),
1354 compiler: Compiler { host: a, stage: 2 }
1358 first(builder.cache.all::<dist::Std>()),
1361 compiler: Compiler { host: a, stage: 2 },
1365 compiler: Compiler { host: a, stage: 2 },
1370 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1374 fn dist_with_hosts() {
1375 let build = Build::new(configure(&["B"], &[]));
1376 let mut builder = Builder::new(&build);
1377 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1379 let a = INTERNER.intern_str("A");
1380 let b = INTERNER.intern_str("B");
1383 first(builder.cache.all::<dist::Docs>()),
1385 dist::Docs { stage: 2, host: a },
1386 dist::Docs { stage: 2, host: b },
1390 first(builder.cache.all::<dist::Mingw>()),
1391 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1394 first(builder.cache.all::<dist::Rustc>()),
1397 compiler: Compiler { host: a, stage: 2 }
1400 compiler: Compiler { host: b, stage: 2 }
1405 first(builder.cache.all::<dist::Std>()),
1408 compiler: Compiler { host: a, stage: 2 },
1412 compiler: Compiler { host: a, stage: 2 },
1417 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1421 fn dist_with_targets_and_hosts() {
1422 let build = Build::new(configure(&["B"], &["C"]));
1423 let mut builder = Builder::new(&build);
1424 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1426 let a = INTERNER.intern_str("A");
1427 let b = INTERNER.intern_str("B");
1428 let c = INTERNER.intern_str("C");
1431 first(builder.cache.all::<dist::Docs>()),
1433 dist::Docs { stage: 2, host: a },
1434 dist::Docs { stage: 2, host: b },
1435 dist::Docs { stage: 2, host: c },
1439 first(builder.cache.all::<dist::Mingw>()),
1441 dist::Mingw { host: a },
1442 dist::Mingw { host: b },
1443 dist::Mingw { host: c },
1447 first(builder.cache.all::<dist::Rustc>()),
1450 compiler: Compiler { host: a, stage: 2 }
1453 compiler: Compiler { host: b, stage: 2 }
1458 first(builder.cache.all::<dist::Std>()),
1461 compiler: Compiler { host: a, stage: 2 },
1465 compiler: Compiler { host: a, stage: 2 },
1469 compiler: Compiler { host: a, stage: 2 },
1474 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1478 fn dist_with_target_flag() {
1479 let mut config = configure(&["B"], &["C"]);
1480 config.run_host_only = false; // as-if --target=C was passed
1481 let build = Build::new(config);
1482 let mut builder = Builder::new(&build);
1483 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1485 let a = INTERNER.intern_str("A");
1486 let b = INTERNER.intern_str("B");
1487 let c = INTERNER.intern_str("C");
1490 first(builder.cache.all::<dist::Docs>()),
1492 dist::Docs { stage: 2, host: a },
1493 dist::Docs { stage: 2, host: b },
1494 dist::Docs { stage: 2, host: c },
1498 first(builder.cache.all::<dist::Mingw>()),
1500 dist::Mingw { host: a },
1501 dist::Mingw { host: b },
1502 dist::Mingw { host: c },
1505 assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1507 first(builder.cache.all::<dist::Std>()),
1510 compiler: Compiler { host: a, stage: 2 },
1514 compiler: Compiler { host: a, stage: 2 },
1518 compiler: Compiler { host: a, stage: 2 },
1523 assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1527 fn dist_with_same_targets_and_hosts() {
1528 let build = Build::new(configure(&["B"], &["B"]));
1529 let mut builder = Builder::new(&build);
1530 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1532 let a = INTERNER.intern_str("A");
1533 let b = INTERNER.intern_str("B");
1536 first(builder.cache.all::<dist::Docs>()),
1538 dist::Docs { stage: 2, host: a },
1539 dist::Docs { stage: 2, host: b },
1543 first(builder.cache.all::<dist::Mingw>()),
1544 &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1547 first(builder.cache.all::<dist::Rustc>()),
1550 compiler: Compiler { host: a, stage: 2 }
1553 compiler: Compiler { host: b, stage: 2 }
1558 first(builder.cache.all::<dist::Std>()),
1561 compiler: Compiler { host: a, stage: 2 },
1565 compiler: Compiler { host: a, stage: 2 },
1570 assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1572 first(builder.cache.all::<compile::Std>()),
1575 compiler: Compiler { host: a, stage: 0 },
1579 compiler: Compiler { host: a, stage: 1 },
1583 compiler: Compiler { host: a, stage: 2 },
1587 compiler: Compiler { host: a, stage: 1 },
1591 compiler: Compiler { host: a, stage: 2 },
1597 first(builder.cache.all::<compile::Test>()),
1600 compiler: Compiler { host: a, stage: 0 },
1604 compiler: Compiler { host: a, stage: 1 },
1608 compiler: Compiler { host: a, stage: 2 },
1612 compiler: Compiler { host: a, stage: 1 },
1616 compiler: Compiler { host: a, stage: 2 },
1622 first(builder.cache.all::<compile::Assemble>()),
1625 target_compiler: Compiler { host: a, stage: 0 },
1628 target_compiler: Compiler { host: a, stage: 1 },
1631 target_compiler: Compiler { host: a, stage: 2 },
1634 target_compiler: Compiler { host: b, stage: 2 },
1641 fn build_default() {
1642 let build = Build::new(configure(&["B"], &["C"]));
1643 let mut builder = Builder::new(&build);
1644 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1646 let a = INTERNER.intern_str("A");
1647 let b = INTERNER.intern_str("B");
1648 let c = INTERNER.intern_str("C");
1650 assert!(!builder.cache.all::<compile::Std>().is_empty());
1651 assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1653 first(builder.cache.all::<compile::Rustc>()),
1656 compiler: Compiler { host: a, stage: 0 },
1660 compiler: Compiler { host: a, stage: 1 },
1664 compiler: Compiler { host: a, stage: 2 },
1668 compiler: Compiler { host: b, stage: 2 },
1672 compiler: Compiler { host: a, stage: 0 },
1676 compiler: Compiler { host: a, stage: 1 },
1680 compiler: Compiler { host: a, stage: 2 },
1684 compiler: Compiler { host: b, stage: 2 },
1691 first(builder.cache.all::<compile::Test>()),
1694 compiler: Compiler { host: a, stage: 0 },
1698 compiler: Compiler { host: a, stage: 1 },
1702 compiler: Compiler { host: a, stage: 2 },
1706 compiler: Compiler { host: b, stage: 2 },
1710 compiler: Compiler { host: a, stage: 0 },
1714 compiler: Compiler { host: a, stage: 1 },
1718 compiler: Compiler { host: a, stage: 2 },
1722 compiler: Compiler { host: b, stage: 2 },
1726 compiler: Compiler { host: a, stage: 2 },
1730 compiler: Compiler { host: b, stage: 2 },
1738 fn build_with_target_flag() {
1739 let mut config = configure(&["B"], &["C"]);
1740 config.run_host_only = false;
1741 let build = Build::new(config);
1742 let mut builder = Builder::new(&build);
1743 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1745 let a = INTERNER.intern_str("A");
1746 let b = INTERNER.intern_str("B");
1747 let c = INTERNER.intern_str("C");
1749 assert!(!builder.cache.all::<compile::Std>().is_empty());
1751 first(builder.cache.all::<compile::Assemble>()),
1754 target_compiler: Compiler { host: a, stage: 0 },
1757 target_compiler: Compiler { host: a, stage: 1 },
1760 target_compiler: Compiler { host: b, stage: 1 },
1763 target_compiler: Compiler { host: a, stage: 2 },
1766 target_compiler: Compiler { host: b, stage: 2 },
1771 first(builder.cache.all::<compile::Rustc>()),
1774 compiler: Compiler { host: a, stage: 0 },
1778 compiler: Compiler { host: a, stage: 1 },
1782 compiler: Compiler { host: a, stage: 0 },
1786 compiler: Compiler { host: a, stage: 1 },
1793 first(builder.cache.all::<compile::Test>()),
1796 compiler: Compiler { host: a, stage: 0 },
1800 compiler: Compiler { host: a, stage: 1 },
1804 compiler: Compiler { host: a, stage: 2 },
1808 compiler: Compiler { host: b, stage: 2 },
1812 compiler: Compiler { host: a, stage: 0 },
1816 compiler: Compiler { host: a, stage: 1 },
1820 compiler: Compiler { host: a, stage: 2 },
1824 compiler: Compiler { host: b, stage: 2 },
1828 compiler: Compiler { host: a, stage: 2 },
1832 compiler: Compiler { host: b, stage: 2 },
1840 fn test_with_no_doc_stage0() {
1841 let mut config = configure(&[], &[]);
1842 config.stage = Some(0);
1843 config.cmd = Subcommand::Test {
1844 paths: vec!["src/libstd".into()],
1848 doc_tests: DocTests::No,
1853 let build = Build::new(config);
1854 let mut builder = Builder::new(&build);
1856 let host = INTERNER.intern_str("A");
1858 builder.run_step_descriptions(
1859 &[StepDescription::from::<test::Crate>()],
1860 &["src/libstd".into()],
1863 // Ensure we don't build any compiler artifacts.
1864 assert!(!builder.cache.contains::<compile::Rustc>());
1866 first(builder.cache.all::<test::Crate>()),
1868 compiler: Compiler { host, stage: 0 },
1871 test_kind: test::TestKind::Test,
1872 krate: INTERNER.intern_str("std"),
1879 let mut config = configure(&[], &[]);
1880 config.exclude = vec![
1881 "src/test/run-pass".into(),
1882 "src/tools/tidy".into(),
1884 config.cmd = Subcommand::Test {
1886 test_args: Vec::new(),
1887 rustc_args: Vec::new(),
1889 doc_tests: DocTests::No,
1894 let build = Build::new(config);
1895 let builder = Builder::new(&build);
1896 builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1898 // Ensure we have really excluded run-pass & tidy
1899 assert!(!builder.cache.contains::<test::RunPass>());
1900 assert!(!builder.cache.contains::<test::Tidy>());
1902 // Ensure other tests are not affected.
1903 assert!(builder.cache.contains::<test::RunPassFullDeps>());
1904 assert!(builder.cache.contains::<test::RustdocUi>());