]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
rustbuild: Assert extended builds don't dist too much
[rust.git] / src / bootstrap / builder.rs
1 use std::any::Any;
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::collections::HashMap;
5 use std::env;
6 use std::fmt::Debug;
7 use std::fs;
8 use std::hash::Hash;
9 use std::ops::Deref;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
13
14 use build_helper::t;
15
16 use crate::cache::{Cache, Interned, INTERNER};
17 use crate::check;
18 use crate::compile;
19 use crate::dist;
20 use crate::doc;
21 use crate::flags::Subcommand;
22 use crate::install;
23 use crate::native;
24 use crate::test;
25 use crate::tool;
26 use crate::util::{self, add_lib_path, exe, libdir};
27 use crate::{Build, DocTests, Mode, GitRepo};
28
29 pub use crate::Compiler;
30
31 use petgraph::graph::NodeIndex;
32 use petgraph::Graph;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<dyn Any>>>,
40     time_spent_on_dependencies: Cell<Duration>,
41     pub paths: Vec<PathBuf>,
42     graph_nodes: RefCell<HashMap<String, NodeIndex>>,
43     graph: RefCell<Graph<String, bool>>,
44     parent: Cell<Option<NodeIndex>>,
45 }
46
47 impl<'a> Deref for Builder<'a> {
48     type Target = Build;
49
50     fn deref(&self) -> &Self::Target {
51         self.build
52     }
53 }
54
55 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
56     /// `PathBuf` when directories are created or to return a `Compiler` once
57     /// it's been assembled.
58     type Output: Clone;
59
60     const DEFAULT: bool = false;
61
62     /// Run this rule for all hosts without cross compiling.
63     const ONLY_HOSTS: bool = false;
64
65     /// Primary function to execute this rule. Can call `builder.ensure()`
66     /// with other steps to run those.
67     fn run(self, builder: &Builder<'_>) -> Self::Output;
68
69     /// When bootstrap is passed a set of paths, this controls whether this rule
70     /// will execute. However, it does not get called in a "default" context
71     /// when we are not passed any paths; in that case, `make_run` is called
72     /// directly.
73     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
74
75     /// Builds up a "root" rule, either as a default rule or from a path passed
76     /// to us.
77     ///
78     /// When path is `None`, we are executing in a context where no paths were
79     /// passed. When `./x.py build` is run, for example, this rule could get
80     /// called if it is in the correct list below with a path of `None`.
81     fn make_run(_run: RunConfig<'_>) {
82         // It is reasonable to not have an implementation of make_run for rules
83         // who do not want to get called from the root context. This means that
84         // they are likely dependencies (e.g., sysroot creation) or similar, and
85         // as such calling them from ./x.py isn't logical.
86         unimplemented!()
87     }
88 }
89
90 pub struct RunConfig<'a> {
91     pub builder: &'a Builder<'a>,
92     pub host: Interned<String>,
93     pub target: Interned<String>,
94     pub path: PathBuf,
95 }
96
97 struct StepDescription {
98     default: bool,
99     only_hosts: bool,
100     should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
101     make_run: fn(RunConfig<'_>),
102     name: &'static str,
103 }
104
105 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
106 pub enum PathSet {
107     Set(BTreeSet<PathBuf>),
108     Suite(PathBuf),
109 }
110
111 impl PathSet {
112     fn empty() -> PathSet {
113         PathSet::Set(BTreeSet::new())
114     }
115
116     fn one<P: Into<PathBuf>>(path: P) -> PathSet {
117         let mut set = BTreeSet::new();
118         set.insert(path.into());
119         PathSet::Set(set)
120     }
121
122     fn has(&self, needle: &Path) -> bool {
123         match self {
124             PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
125             PathSet::Suite(suite) => suite.ends_with(needle),
126         }
127     }
128
129     fn path(&self, builder: &Builder<'_>) -> PathBuf {
130         match self {
131             PathSet::Set(set) => set
132                 .iter()
133                 .next()
134                 .unwrap_or(&builder.build.src)
135                 .to_path_buf(),
136             PathSet::Suite(path) => PathBuf::from(path),
137         }
138     }
139 }
140
141 impl StepDescription {
142     fn from<S: Step>() -> StepDescription {
143         StepDescription {
144             default: S::DEFAULT,
145             only_hosts: S::ONLY_HOSTS,
146             should_run: S::should_run,
147             make_run: S::make_run,
148             name: unsafe { ::std::intrinsics::type_name::<S>() },
149         }
150     }
151
152     fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
153         if builder.config.exclude.iter().any(|e| pathset.has(e)) {
154             eprintln!("Skipping {:?} because it is excluded", pathset);
155             return;
156         } else if !builder.config.exclude.is_empty() {
157             eprintln!(
158                 "{:?} not skipped for {:?} -- not in {:?}",
159                 pathset, self.name, builder.config.exclude
160             );
161         }
162         let hosts = &builder.hosts;
163
164         // Determine the targets participating in this rule.
165         let targets = if self.only_hosts {
166             if !builder.config.run_host_only {
167                 return; // don't run anything
168             } else {
169                 &builder.hosts
170             }
171         } else {
172             &builder.targets
173         };
174
175         for host in hosts {
176             for target in targets {
177                 let run = RunConfig {
178                     builder,
179                     path: pathset.path(builder),
180                     host: *host,
181                     target: *target,
182                 };
183                 (self.make_run)(run);
184             }
185         }
186     }
187
188     fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
189         let should_runs = v
190             .iter()
191             .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
192             .collect::<Vec<_>>();
193
194         // sanity checks on rules
195         for (desc, should_run) in v.iter().zip(&should_runs) {
196             assert!(
197                 !should_run.paths.is_empty(),
198                 "{:?} should have at least one pathset",
199                 desc.name
200             );
201         }
202
203         if paths.is_empty() {
204             for (desc, should_run) in v.iter().zip(should_runs) {
205                 if desc.default && should_run.is_really_default {
206                     for pathset in &should_run.paths {
207                         desc.maybe_run(builder, pathset);
208                     }
209                 }
210             }
211         } else {
212             for path in paths {
213                 // strip CurDir prefix if present
214                 let path = match path.strip_prefix(".") {
215                     Ok(p) => p,
216                     Err(_) => path,
217                 };
218
219                 let mut attempted_run = false;
220                 for (desc, should_run) in v.iter().zip(&should_runs) {
221                     if let Some(suite) = should_run.is_suite_path(path) {
222                         attempted_run = true;
223                         desc.maybe_run(builder, suite);
224                     } else if let Some(pathset) = should_run.pathset_for_path(path) {
225                         attempted_run = true;
226                         desc.maybe_run(builder, pathset);
227                     }
228                 }
229
230                 if !attempted_run {
231                     panic!("Error: no rules matched {}.", path.display());
232                 }
233             }
234         }
235     }
236 }
237
238 #[derive(Clone)]
239 pub struct ShouldRun<'a> {
240     pub builder: &'a Builder<'a>,
241     // use a BTreeSet to maintain sort order
242     paths: BTreeSet<PathSet>,
243
244     // If this is a default rule, this is an additional constraint placed on
245     // its run. Generally something like compiler docs being enabled.
246     is_really_default: bool,
247 }
248
249 impl<'a> ShouldRun<'a> {
250     fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
251         ShouldRun {
252             builder,
253             paths: BTreeSet::new(),
254             is_really_default: true, // by default no additional conditions
255         }
256     }
257
258     pub fn default_condition(mut self, cond: bool) -> Self {
259         self.is_really_default = cond;
260         self
261     }
262
263     // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
264     // ever be used, but as we transition to having all rules properly handle passing krate(...) by
265     // actually doing something different for every crate passed.
266     pub fn all_krates(mut self, name: &str) -> Self {
267         let mut set = BTreeSet::new();
268         for krate in self.builder.in_tree_crates(name) {
269             set.insert(PathBuf::from(&krate.path));
270         }
271         self.paths.insert(PathSet::Set(set));
272         self
273     }
274
275     pub fn krate(mut self, name: &str) -> Self {
276         for krate in self.builder.in_tree_crates(name) {
277             self.paths.insert(PathSet::one(&krate.path));
278         }
279         self
280     }
281
282     // single, non-aliased path
283     pub fn path(self, path: &str) -> Self {
284         self.paths(&[path])
285     }
286
287     // multiple aliases for the same job
288     pub fn paths(mut self, paths: &[&str]) -> Self {
289         self.paths
290             .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
291         self
292     }
293
294     pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
295         self.paths.iter().find(|pathset| match pathset {
296             PathSet::Suite(p) => path.starts_with(p),
297             PathSet::Set(_) => false,
298         })
299     }
300
301     pub fn suite_path(mut self, suite: &str) -> Self {
302         self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
303         self
304     }
305
306     // allows being more explicit about why should_run in Step returns the value passed to it
307     pub fn never(mut self) -> ShouldRun<'a> {
308         self.paths.insert(PathSet::empty());
309         self
310     }
311
312     fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
313         self.paths.iter().find(|pathset| pathset.has(path))
314     }
315 }
316
317 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
318 pub enum Kind {
319     Build,
320     Check,
321     Test,
322     Bench,
323     Dist,
324     Doc,
325     Install,
326 }
327
328 impl<'a> Builder<'a> {
329     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
330         macro_rules! describe {
331             ($($rule:ty),+ $(,)?) => {{
332                 vec![$(StepDescription::from::<$rule>()),+]
333             }};
334         }
335         match kind {
336             Kind::Build => describe!(
337                 compile::Std,
338                 compile::Test,
339                 compile::Rustc,
340                 compile::CodegenBackend,
341                 compile::StartupObjects,
342                 tool::BuildManifest,
343                 tool::Rustbook,
344                 tool::ErrorIndex,
345                 tool::UnstableBookGen,
346                 tool::Tidy,
347                 tool::Linkchecker,
348                 tool::CargoTest,
349                 tool::Compiletest,
350                 tool::RemoteTestServer,
351                 tool::RemoteTestClient,
352                 tool::RustInstaller,
353                 tool::Cargo,
354                 tool::Rls,
355                 tool::Rustdoc,
356                 tool::Clippy,
357                 native::Llvm,
358                 tool::Rustfmt,
359                 tool::Miri,
360                 native::Lld
361             ),
362             Kind::Check => describe!(
363                 check::Std,
364                 check::Test,
365                 check::Rustc,
366                 check::CodegenBackend,
367                 check::Rustdoc
368             ),
369             Kind::Test => describe!(
370                 test::Tidy,
371                 test::Ui,
372                 test::RunPass,
373                 test::CompileFail,
374                 test::RunFail,
375                 test::RunPassValgrind,
376                 test::MirOpt,
377                 test::Codegen,
378                 test::CodegenUnits,
379                 test::Assembly,
380                 test::Incremental,
381                 test::Debuginfo,
382                 test::UiFullDeps,
383                 test::RunPassFullDeps,
384                 test::Rustdoc,
385                 test::Pretty,
386                 test::RunPassPretty,
387                 test::RunFailPretty,
388                 test::RunPassValgrindPretty,
389                 test::Crate,
390                 test::CrateLibrustc,
391                 test::CrateRustdoc,
392                 test::Linkcheck,
393                 test::Cargotest,
394                 test::Cargo,
395                 test::Rls,
396                 test::ErrorIndex,
397                 test::Distcheck,
398                 test::RunMakeFullDeps,
399                 test::Nomicon,
400                 test::Reference,
401                 test::RustdocBook,
402                 test::RustByExample,
403                 test::TheBook,
404                 test::UnstableBook,
405                 test::RustcBook,
406                 test::EmbeddedBook,
407                 test::EditionGuide,
408                 test::Rustfmt,
409                 test::Miri,
410                 test::Clippy,
411                 test::CompiletestTest,
412                 test::RustdocJSStd,
413                 test::RustdocJSNotStd,
414                 test::RustdocTheme,
415                 test::RustdocUi,
416                 // Run bootstrap close to the end as it's unlikely to fail
417                 test::Bootstrap,
418                 // Run run-make last, since these won't pass without make on Windows
419                 test::RunMake,
420             ),
421             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
422             Kind::Doc => describe!(
423                 doc::UnstableBook,
424                 doc::UnstableBookGen,
425                 doc::TheBook,
426                 doc::Standalone,
427                 doc::Std,
428                 doc::Test,
429                 doc::WhitelistedRustc,
430                 doc::Rustc,
431                 doc::Rustdoc,
432                 doc::ErrorIndex,
433                 doc::Nomicon,
434                 doc::Reference,
435                 doc::RustdocBook,
436                 doc::RustByExample,
437                 doc::RustcBook,
438                 doc::CargoBook,
439                 doc::EmbeddedBook,
440                 doc::EditionGuide,
441             ),
442             Kind::Dist => describe!(
443                 dist::Docs,
444                 dist::RustcDocs,
445                 dist::Mingw,
446                 dist::Rustc,
447                 dist::DebuggerScripts,
448                 dist::Std,
449                 dist::Analysis,
450                 dist::Src,
451                 dist::PlainSourceTarball,
452                 dist::Cargo,
453                 dist::Rls,
454                 dist::Rustfmt,
455                 dist::Clippy,
456                 dist::Miri,
457                 dist::LlvmTools,
458                 dist::Lldb,
459                 dist::Extended,
460                 dist::HashSign
461             ),
462             Kind::Install => describe!(
463                 install::Docs,
464                 install::Std,
465                 install::Cargo,
466                 install::Rls,
467                 install::Rustfmt,
468                 install::Clippy,
469                 install::Miri,
470                 install::Analysis,
471                 install::Src,
472                 install::Rustc
473             ),
474         }
475     }
476
477     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
478         let kind = match subcommand {
479             "build" => Kind::Build,
480             "doc" => Kind::Doc,
481             "test" => Kind::Test,
482             "bench" => Kind::Bench,
483             "dist" => Kind::Dist,
484             "install" => Kind::Install,
485             _ => return None,
486         };
487
488         let builder = Builder {
489             build,
490             top_stage: build.config.stage.unwrap_or(2),
491             kind,
492             cache: Cache::new(),
493             stack: RefCell::new(Vec::new()),
494             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
495             paths: vec![],
496             graph_nodes: RefCell::new(HashMap::new()),
497             graph: RefCell::new(Graph::new()),
498             parent: Cell::new(None),
499         };
500
501         let builder = &builder;
502         let mut should_run = ShouldRun::new(builder);
503         for desc in Builder::get_step_descriptions(builder.kind) {
504             should_run = (desc.should_run)(should_run);
505         }
506         let mut help = String::from("Available paths:\n");
507         for pathset in should_run.paths {
508             if let PathSet::Set(set) = pathset {
509                 set.iter().for_each(|path| {
510                     help.push_str(
511                         format!("    ./x.py {} {}\n", subcommand, path.display()).as_str(),
512                     )
513                 })
514             }
515         }
516         Some(help)
517     }
518
519     pub fn new(build: &Build) -> Builder<'_> {
520         let (kind, paths) = match build.config.cmd {
521             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
522             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
523             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
524             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
525             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
526             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
527             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
528             Subcommand::Clean { .. } => panic!(),
529         };
530
531         let builder = Builder {
532             build,
533             top_stage: build.config.stage.unwrap_or(2),
534             kind,
535             cache: Cache::new(),
536             stack: RefCell::new(Vec::new()),
537             time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
538             paths: paths.to_owned(),
539             graph_nodes: RefCell::new(HashMap::new()),
540             graph: RefCell::new(Graph::new()),
541             parent: Cell::new(None),
542         };
543
544         if kind == Kind::Dist {
545             assert!(
546                 !builder.config.test_miri,
547                 "Do not distribute with miri enabled.\n\
548                 The distributed libraries would include all MIR (increasing binary size).
549                 The distributed MIR would include validation statements."
550             );
551         }
552
553         builder
554     }
555
556     pub fn execute_cli(&self) -> Graph<String, bool> {
557         self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
558         self.graph.borrow().clone()
559     }
560
561     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
562         let paths = paths.unwrap_or(&[]);
563         self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
564     }
565
566     fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
567         StepDescription::run(v, self, paths);
568     }
569
570     /// Obtain a compiler at a given stage and for a given host. Explicitly does
571     /// not take `Compiler` since all `Compiler` instances are meant to be
572     /// obtained through this function, since it ensures that they are valid
573     /// (i.e., built and assembled).
574     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
575         self.ensure(compile::Assemble {
576             target_compiler: Compiler { stage, host },
577         })
578     }
579
580     /// Similar to `compiler`, except handles the full-bootstrap option to
581     /// silently use the stage1 compiler instead of a stage2 compiler if one is
582     /// requested.
583     ///
584     /// Note that this does *not* have the side effect of creating
585     /// `compiler(stage, host)`, unlike `compiler` above which does have such
586     /// a side effect. The returned compiler here can only be used to compile
587     /// new artifacts, it can't be used to rely on the presence of a particular
588     /// sysroot.
589     ///
590     /// See `force_use_stage1` for documentation on what each argument is.
591     pub fn compiler_for(&self, stage: u32, host: Interned<String>, target: Interned<String>) -> Compiler {
592         if self.build.force_use_stage1(Compiler { stage, host }, target) {
593             self.compiler(1, self.config.build)
594         } else {
595             self.compiler(stage, host)
596         }
597     }
598
599     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
600         self.ensure(compile::Sysroot { compiler })
601     }
602
603     /// Returns the libdir where the standard library and other artifacts are
604     /// found for a compiler's sysroot.
605     pub fn sysroot_libdir(
606         &self,
607         compiler: Compiler,
608         target: Interned<String>,
609     ) -> Interned<PathBuf> {
610         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
611         struct Libdir {
612             compiler: Compiler,
613             target: Interned<String>,
614         }
615         impl Step for Libdir {
616             type Output = Interned<PathBuf>;
617
618             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
619                 run.never()
620             }
621
622             fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
623                 let compiler = self.compiler;
624                 let config = &builder.build.config;
625                 let lib = if compiler.stage >= 1 && config.libdir_relative().is_some() {
626                     builder.build.config.libdir_relative().unwrap()
627                 } else {
628                     Path::new("lib")
629                 };
630                 let sysroot = builder
631                     .sysroot(self.compiler)
632                     .join(lib)
633                     .join("rustlib")
634                     .join(self.target)
635                     .join("lib");
636                 let _ = fs::remove_dir_all(&sysroot);
637                 t!(fs::create_dir_all(&sysroot));
638                 INTERNER.intern_path(sysroot)
639             }
640         }
641         self.ensure(Libdir { compiler, target })
642     }
643
644     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
645         self.sysroot_libdir(compiler, compiler.host)
646             .with_file_name(self.config.rust_codegen_backends_dir.clone())
647     }
648
649     /// Returns the compiler's libdir where it stores the dynamic libraries that
650     /// it itself links against.
651     ///
652     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
653     /// Windows.
654     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
655         if compiler.is_snapshot(self) {
656             self.rustc_snapshot_libdir()
657         } else {
658             match self.config.libdir_relative() {
659                 Some(relative_libdir) if compiler.stage >= 1
660                     => self.sysroot(compiler).join(relative_libdir),
661                 _ => self.sysroot(compiler).join(libdir(&compiler.host))
662             }
663         }
664     }
665
666     /// Returns the compiler's relative libdir where it stores the dynamic libraries that
667     /// it itself links against.
668     ///
669     /// For example this returns `lib` on Unix and `bin` on
670     /// Windows.
671     pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
672         if compiler.is_snapshot(self) {
673             libdir(&self.config.build).as_ref()
674         } else {
675             match self.config.libdir_relative() {
676                 Some(relative_libdir) if compiler.stage >= 1
677                     => relative_libdir,
678                 _ => libdir(&compiler.host).as_ref()
679             }
680         }
681     }
682
683     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
684     /// library lookup path.
685     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
686         // Windows doesn't need dylib path munging because the dlls for the
687         // compiler live next to the compiler and the system will find them
688         // automatically.
689         if cfg!(windows) {
690             return;
691         }
692
693         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
694     }
695
696     /// Gets a path to the compiler specified.
697     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
698         if compiler.is_snapshot(self) {
699             self.initial_rustc.clone()
700         } else {
701             self.sysroot(compiler)
702                 .join("bin")
703                 .join(exe("rustc", &compiler.host))
704         }
705     }
706
707     /// Gets the paths to all of the compiler's codegen backends.
708     fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
709         fs::read_dir(self.sysroot_codegen_backends(compiler))
710             .into_iter()
711             .flatten()
712             .filter_map(Result::ok)
713             .map(|entry| entry.path())
714     }
715
716     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
717         self.ensure(tool::Rustdoc { compiler })
718     }
719
720     pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
721         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
722         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
723             .env("RUSTC_SYSROOT", self.sysroot(compiler))
724             // Note that this is *not* the sysroot_libdir because rustdoc must be linked
725             // equivalently to rustc.
726             .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
727             .env("CFG_RELEASE_CHANNEL", &self.config.channel)
728             .env("RUSTDOC_REAL", self.rustdoc(compiler))
729             .env("RUSTDOC_CRATE_VERSION", self.rust_version())
730             .env("RUSTC_BOOTSTRAP", "1");
731
732         // Remove make-related flags that can cause jobserver problems.
733         cmd.env_remove("MAKEFLAGS");
734         cmd.env_remove("MFLAGS");
735
736         if let Some(linker) = self.linker(compiler.host) {
737             cmd.env("RUSTC_TARGET_LINKER", linker);
738         }
739         cmd
740     }
741
742     /// Prepares an invocation of `cargo` to be run.
743     ///
744     /// This will create a `Command` that represents a pending execution of
745     /// Cargo. This cargo will be configured to use `compiler` as the actual
746     /// rustc compiler, its output will be scoped by `mode`'s output directory,
747     /// it will pass the `--target` flag for the specified `target`, and will be
748     /// executing the Cargo command `cmd`.
749     pub fn cargo(
750         &self,
751         compiler: Compiler,
752         mode: Mode,
753         target: Interned<String>,
754         cmd: &str,
755     ) -> Command {
756         let mut cargo = Command::new(&self.initial_cargo);
757         let out_dir = self.stage_out(compiler, mode);
758
759         // command specific path, we call clear_if_dirty with this
760         let mut my_out = match cmd {
761             "build" => self.cargo_out(compiler, mode, target),
762
763             // This is the intended out directory for crate documentation.
764             "doc" | "rustdoc" =>  self.crate_doc_out(target),
765
766             _ => self.stage_out(compiler, mode),
767         };
768
769         // This is for the original compiler, but if we're forced to use stage 1, then
770         // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
771         // we copy the libs forward.
772         let cmp = self.compiler_for(compiler.stage, compiler.host, target);
773
774         let libstd_stamp = match cmd {
775             "check" => check::libstd_stamp(self, cmp, target),
776             _ => compile::libstd_stamp(self, cmp, target),
777         };
778
779         let libtest_stamp = match cmd {
780             "check" => check::libtest_stamp(self, cmp, target),
781             _ => compile::libstd_stamp(self, cmp, target),
782         };
783
784         let librustc_stamp = match cmd {
785             "check" => check::librustc_stamp(self, cmp, target),
786             _ => compile::librustc_stamp(self, cmp, target),
787         };
788
789         if cmd == "doc" || cmd == "rustdoc" {
790             if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
791                 // This is the intended out directory for compiler documentation.
792                 my_out = self.compiler_doc_out(target);
793             }
794             let rustdoc = self.rustdoc(compiler);
795             self.clear_if_dirty(&my_out, &rustdoc);
796         } else if cmd != "test" {
797             match mode {
798                 Mode::Std => {
799                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
800                     for backend in self.codegen_backends(compiler) {
801                         self.clear_if_dirty(&my_out, &backend);
802                     }
803                 },
804                 Mode::Test => {
805                     self.clear_if_dirty(&my_out, &libstd_stamp);
806                 },
807                 Mode::Rustc => {
808                     self.clear_if_dirty(&my_out, &self.rustc(compiler));
809                     self.clear_if_dirty(&my_out, &libstd_stamp);
810                     self.clear_if_dirty(&my_out, &libtest_stamp);
811                 },
812                 Mode::Codegen => {
813                     self.clear_if_dirty(&my_out, &librustc_stamp);
814                 },
815                 Mode::ToolBootstrap => { },
816                 Mode::ToolStd => {
817                     self.clear_if_dirty(&my_out, &libstd_stamp);
818                 },
819                 Mode::ToolTest => {
820                     self.clear_if_dirty(&my_out, &libstd_stamp);
821                     self.clear_if_dirty(&my_out, &libtest_stamp);
822                 },
823                 Mode::ToolRustc => {
824                     self.clear_if_dirty(&my_out, &libstd_stamp);
825                     self.clear_if_dirty(&my_out, &libtest_stamp);
826                     self.clear_if_dirty(&my_out, &librustc_stamp);
827                 },
828             }
829         }
830
831         cargo
832             .env("CARGO_TARGET_DIR", out_dir)
833             .arg(cmd);
834
835         // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
836         // needs to not accidentally link to libLLVM in stage0/lib.
837         cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
838         if let Some(e) = env::var_os(util::dylib_path_var()) {
839             cargo.env("REAL_LIBRARY_PATH", e);
840         }
841
842         if cmd != "install" {
843             cargo.arg("--target")
844                  .arg(target);
845         } else {
846             assert_eq!(target, compiler.host);
847         }
848
849         // Set a flag for `check` so that certain build scripts can do less work
850         // (e.g., not building/requiring LLVM).
851         if cmd == "check" {
852             cargo.env("RUST_CHECK", "1");
853         }
854
855         match mode {
856             Mode::Std | Mode::Test | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTest=> {},
857             Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
858                 // Build proc macros both for the host and the target
859                 if target != compiler.host && cmd != "check" {
860                     cargo.arg("-Zdual-proc-macros");
861                     cargo.env("RUST_DUAL_PROC_MACROS", "1");
862                 }
863             },
864         }
865
866         cargo.arg("-j").arg(self.jobs().to_string());
867         // Remove make-related flags to ensure Cargo can correctly set things up
868         cargo.env_remove("MAKEFLAGS");
869         cargo.env_remove("MFLAGS");
870
871         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
872         // Force cargo to output binaries with disambiguating hashes in the name
873         let mut metadata = if compiler.stage == 0 {
874             // Treat stage0 like a special channel, whether it's a normal prior-
875             // release rustc or a local rebuild with the same version, so we
876             // never mix these libraries by accident.
877             "bootstrap".to_string()
878         } else {
879             self.config.channel.to_string()
880         };
881         // We want to make sure that none of the dependencies between
882         // std/test/rustc unify with one another. This is done for weird linkage
883         // reasons but the gist of the problem is that if librustc, libtest, and
884         // libstd all depend on libc from crates.io (which they actually do) we
885         // want to make sure they all get distinct versions. Things get really
886         // weird if we try to unify all these dependencies right now, namely
887         // around how many times the library is linked in dynamic libraries and
888         // such. If rustc were a static executable or if we didn't ship dylibs
889         // this wouldn't be a problem, but we do, so it is. This is in general
890         // just here to make sure things build right. If you can remove this and
891         // things still build right, please do!
892         match mode {
893             Mode::Std => metadata.push_str("std"),
894             Mode::Test => metadata.push_str("test"),
895             _ => {},
896         }
897         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
898
899         let stage;
900         if compiler.stage == 0 && self.local_rebuild {
901             // Assume the local-rebuild rustc already has stage1 features.
902             stage = 1;
903         } else {
904             stage = compiler.stage;
905         }
906
907         let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
908         if stage != 0 {
909             let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
910             if !extra_args.is_empty() {
911                 extra_args.push_str(" ");
912             }
913             extra_args.push_str(&s);
914         }
915
916         if !extra_args.is_empty() {
917             cargo.env(
918                 "RUSTFLAGS",
919                 format!(
920                     "{} {}",
921                     env::var("RUSTFLAGS").unwrap_or_default(),
922                     extra_args
923                 ),
924             );
925         }
926
927         let want_rustdoc = self.doc_tests != DocTests::No;
928
929         // We synthetically interpret a stage0 compiler used to build tools as a
930         // "raw" compiler in that it's the exact snapshot we download. Normally
931         // the stage0 build means it uses libraries build by the stage0
932         // compiler, but for tools we just use the precompiled libraries that
933         // we've downloaded
934         let use_snapshot = mode == Mode::ToolBootstrap;
935         assert!(!use_snapshot || stage == 0 || self.local_rebuild);
936
937         let maybe_sysroot = self.sysroot(compiler);
938         let sysroot = if use_snapshot {
939             self.rustc_snapshot_sysroot()
940         } else {
941             &maybe_sysroot
942         };
943         let libdir = self.rustc_libdir(compiler);
944
945         // Customize the compiler we're running. Specify the compiler to cargo
946         // as our shim and then pass it some various options used to configure
947         // how the actual compiler itself is called.
948         //
949         // These variables are primarily all read by
950         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
951         cargo
952             .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
953             .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
954             .env("RUSTC_REAL", self.rustc(compiler))
955             .env("RUSTC_STAGE", stage.to_string())
956             .env(
957                 "RUSTC_DEBUG_ASSERTIONS",
958                 self.config.rust_debug_assertions.to_string(),
959             )
960             .env("RUSTC_SYSROOT", &sysroot)
961             .env("RUSTC_LIBDIR", &libdir)
962             .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
963             .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
964             .env(
965                 "RUSTDOC_REAL",
966                 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
967                     self.rustdoc(compiler)
968                 } else {
969                     PathBuf::from("/path/to/nowhere/rustdoc/not/required")
970                 },
971             )
972             .env("TEST_MIRI", self.config.test_miri.to_string())
973             .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
974
975         if let Some(host_linker) = self.linker(compiler.host) {
976             cargo.env("RUSTC_HOST_LINKER", host_linker);
977         }
978         if let Some(target_linker) = self.linker(target) {
979             cargo.env("RUSTC_TARGET_LINKER", target_linker);
980         }
981         if let Some(ref error_format) = self.config.rustc_error_format {
982             cargo.env("RUSTC_ERROR_FORMAT", error_format);
983         }
984         if cmd != "build" && cmd != "check" && cmd != "rustc" && want_rustdoc {
985             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
986         }
987
988         if mode.is_tool() {
989             // Tools like cargo and rls don't get debuginfo by default right now, but this can be
990             // enabled in the config.  Adding debuginfo makes them several times larger.
991             if self.config.rust_debuginfo_tools {
992                 cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
993                 cargo.env(
994                     "RUSTC_DEBUGINFO_LINES",
995                     self.config.rust_debuginfo_lines.to_string(),
996                 );
997             }
998         } else {
999             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
1000             cargo.env(
1001                 "RUSTC_DEBUGINFO_LINES",
1002                 self.config.rust_debuginfo_lines.to_string(),
1003             );
1004             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1005
1006             // Currently the compiler depends on crates from crates.io, and
1007             // then other crates can depend on the compiler (e.g., proc-macro
1008             // crates). Let's say, for example that rustc itself depends on the
1009             // bitflags crate. If an external crate then depends on the
1010             // bitflags crate as well, we need to make sure they don't
1011             // conflict, even if they pick the same version of bitflags. We'll
1012             // want to make sure that e.g., a plugin and rustc each get their
1013             // own copy of bitflags.
1014
1015             // Cargo ensures that this works in general through the -C metadata
1016             // flag. This flag will frob the symbols in the binary to make sure
1017             // they're different, even though the source code is the exact
1018             // same. To solve this problem for the compiler we extend Cargo's
1019             // already-passed -C metadata flag with our own. Our rustc.rs
1020             // wrapper around the actual rustc will detect -C metadata being
1021             // passed and frob it with this extra string we're passing in.
1022             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
1023         }
1024
1025         if let Some(x) = self.crt_static(target) {
1026             cargo.env("RUSTC_CRT_STATIC", x.to_string());
1027         }
1028
1029         if let Some(x) = self.crt_static(compiler.host) {
1030             cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1031         }
1032
1033         if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1034             cargo.env("RUSTC_DEBUGINFO_MAP", map);
1035         }
1036
1037         // Enable usage of unstable features
1038         cargo.env("RUSTC_BOOTSTRAP", "1");
1039         self.add_rust_test_threads(&mut cargo);
1040
1041         // Almost all of the crates that we compile as part of the bootstrap may
1042         // have a build script, including the standard library. To compile a
1043         // build script, however, it itself needs a standard library! This
1044         // introduces a bit of a pickle when we're compiling the standard
1045         // library itself.
1046         //
1047         // To work around this we actually end up using the snapshot compiler
1048         // (stage0) for compiling build scripts of the standard library itself.
1049         // The stage0 compiler is guaranteed to have a libstd available for use.
1050         //
1051         // For other crates, however, we know that we've already got a standard
1052         // library up and running, so we can use the normal compiler to compile
1053         // build scripts in that situation.
1054         if mode == Mode::Std {
1055             cargo
1056                 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1057                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1058         } else {
1059             cargo
1060                 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1061                 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1062         }
1063
1064         if self.config.incremental {
1065             cargo.env("CARGO_INCREMENTAL", "1");
1066         } else {
1067             // Don't rely on any default setting for incr. comp. in Cargo
1068             cargo.env("CARGO_INCREMENTAL", "0");
1069         }
1070
1071         if let Some(ref on_fail) = self.config.on_fail {
1072             cargo.env("RUSTC_ON_FAIL", on_fail);
1073         }
1074
1075         if self.config.print_step_timings {
1076             cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1077         }
1078
1079         if self.config.backtrace_on_ice {
1080             cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1081         }
1082
1083         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1084
1085         if self.config.deny_warnings {
1086             cargo.env("RUSTC_DENY_WARNINGS", "1");
1087         }
1088
1089         // Throughout the build Cargo can execute a number of build scripts
1090         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1091         // obtained previously to those build scripts.
1092         // Build scripts use either the `cc` crate or `configure/make` so we pass
1093         // the options through environment variables that are fetched and understood by both.
1094         //
1095         // FIXME: the guard against msvc shouldn't need to be here
1096         if target.contains("msvc") {
1097             if let Some(ref cl) = self.config.llvm_clang_cl {
1098                 cargo.env("CC", cl).env("CXX", cl);
1099             }
1100         } else {
1101             let ccache = self.config.ccache.as_ref();
1102             let ccacheify = |s: &Path| {
1103                 let ccache = match ccache {
1104                     Some(ref s) => s,
1105                     None => return s.display().to_string(),
1106                 };
1107                 // FIXME: the cc-rs crate only recognizes the literal strings
1108                 // `ccache` and `sccache` when doing caching compilations, so we
1109                 // mirror that here. It should probably be fixed upstream to
1110                 // accept a new env var or otherwise work with custom ccache
1111                 // vars.
1112                 match &ccache[..] {
1113                     "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1114                     _ => s.display().to_string(),
1115                 }
1116             };
1117             let cc = ccacheify(&self.cc(target));
1118             cargo.env(format!("CC_{}", target), &cc);
1119
1120             let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1121             cargo
1122                 .env(format!("CFLAGS_{}", target), cflags.clone());
1123
1124             if let Some(ar) = self.ar(target) {
1125                 let ranlib = format!("{} s", ar.display());
1126                 cargo
1127                     .env(format!("AR_{}", target), ar)
1128                     .env(format!("RANLIB_{}", target), ranlib);
1129             }
1130
1131             if let Ok(cxx) = self.cxx(target) {
1132                 let cxx = ccacheify(&cxx);
1133                 cargo
1134                     .env(format!("CXX_{}", target), &cxx)
1135                     .env(format!("CXXFLAGS_{}", target), cflags);
1136             }
1137         }
1138
1139         if (cmd == "build" || cmd == "rustc")
1140             && mode == Mode::Std
1141             && self.config.extended
1142             && compiler.is_final_stage(self)
1143         {
1144             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
1145         }
1146
1147         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1148         cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1149
1150         // Environment variables *required* throughout the build
1151         //
1152         // FIXME: should update code to not require this env var
1153         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1154
1155         // Set this for all builds to make sure doc builds also get it.
1156         cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1157
1158         // This one's a bit tricky. As of the time of this writing the compiler
1159         // links to the `winapi` crate on crates.io. This crate provides raw
1160         // bindings to Windows system functions, sort of like libc does for
1161         // Unix. This crate also, however, provides "import libraries" for the
1162         // MinGW targets. There's an import library per dll in the windows
1163         // distribution which is what's linked to. These custom import libraries
1164         // are used because the winapi crate can reference Windows functions not
1165         // present in the MinGW import libraries.
1166         //
1167         // For example MinGW may ship libdbghelp.a, but it may not have
1168         // references to all the functions in the dbghelp dll. Instead the
1169         // custom import library for dbghelp in the winapi crates has all this
1170         // information.
1171         //
1172         // Unfortunately for us though the import libraries are linked by
1173         // default via `-ldylib=winapi_foo`. That is, they're linked with the
1174         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1175         // conflict with the system MinGW ones). This consequently means that
1176         // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1177         // DLL) when linked against *again*, for example with procedural macros
1178         // or plugins, will trigger the propagation logic of `-ldylib`, passing
1179         // `-lwinapi_foo` to the linker again. This isn't actually available in
1180         // our distribution, however, so the link fails.
1181         //
1182         // To solve this problem we tell winapi to not use its bundled import
1183         // libraries. This means that it will link to the system MinGW import
1184         // libraries by default, and the `-ldylib=foo` directives will still get
1185         // passed to the final linker, but they'll look like `-lfoo` which can
1186         // be resolved because MinGW has the import library. The downside is we
1187         // don't get newer functions from Windows, but we don't use any of them
1188         // anyway.
1189         if !mode.is_tool() {
1190             cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1191         }
1192
1193         for _ in 1..self.verbosity {
1194             cargo.arg("-v");
1195         }
1196
1197         match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1198             (Mode::Std, Some(n), _) |
1199             (Mode::Test, Some(n), _) |
1200             (_, _, Some(n)) => {
1201                 cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
1202             }
1203             _ => {
1204                 // Don't set anything
1205             }
1206         }
1207
1208         if self.config.rust_optimize {
1209             // FIXME: cargo bench/install do not accept `--release`
1210             if cmd != "bench" && cmd != "install" {
1211                 cargo.arg("--release");
1212             }
1213         }
1214
1215         if self.config.locked_deps {
1216             cargo.arg("--locked");
1217         }
1218         if self.config.vendor || self.is_sudo {
1219             cargo.arg("--frozen");
1220         }
1221
1222         self.ci_env.force_coloring_in_ci(&mut cargo);
1223
1224         cargo
1225     }
1226
1227     /// Ensure that a given step is built, returning its output. This will
1228     /// cache the step, so it is safe (and good!) to call this as often as
1229     /// needed to ensure that all dependencies are built.
1230     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1231         {
1232             let mut stack = self.stack.borrow_mut();
1233             for stack_step in stack.iter() {
1234                 // should skip
1235                 if stack_step
1236                     .downcast_ref::<S>()
1237                     .map_or(true, |stack_step| *stack_step != step)
1238                 {
1239                     continue;
1240                 }
1241                 let mut out = String::new();
1242                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1243                 for el in stack.iter().rev() {
1244                     out += &format!("\t{:?}\n", el);
1245                 }
1246                 panic!(out);
1247             }
1248             if let Some(out) = self.cache.get(&step) {
1249                 self.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
1250
1251                 {
1252                     let mut graph = self.graph.borrow_mut();
1253                     let parent = self.parent.get();
1254                     let us = *self
1255                         .graph_nodes
1256                         .borrow_mut()
1257                         .entry(format!("{:?}", step))
1258                         .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1259                     if let Some(parent) = parent {
1260                         graph.add_edge(parent, us, false);
1261                     }
1262                 }
1263
1264                 return out;
1265             }
1266             self.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
1267             stack.push(Box::new(step.clone()));
1268         }
1269
1270         let prev_parent = self.parent.get();
1271
1272         {
1273             let mut graph = self.graph.borrow_mut();
1274             let parent = self.parent.get();
1275             let us = *self
1276                 .graph_nodes
1277                 .borrow_mut()
1278                 .entry(format!("{:?}", step))
1279                 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1280             self.parent.set(Some(us));
1281             if let Some(parent) = parent {
1282                 graph.add_edge(parent, us, true);
1283             }
1284         }
1285
1286         let (out, dur) = {
1287             let start = Instant::now();
1288             let zero = Duration::new(0, 0);
1289             let parent = self.time_spent_on_dependencies.replace(zero);
1290             let out = step.clone().run(self);
1291             let dur = start.elapsed();
1292             let deps = self.time_spent_on_dependencies.replace(parent + dur);
1293             (out, dur - deps)
1294         };
1295
1296         self.parent.set(prev_parent);
1297
1298         if self.config.print_step_timings && dur > Duration::from_millis(100) {
1299             println!(
1300                 "[TIMING] {:?} -- {}.{:03}",
1301                 step,
1302                 dur.as_secs(),
1303                 dur.subsec_nanos() / 1_000_000
1304             );
1305         }
1306
1307         {
1308             let mut stack = self.stack.borrow_mut();
1309             let cur_step = stack.pop().expect("step stack empty");
1310             assert_eq!(cur_step.downcast_ref(), Some(&step));
1311         }
1312         self.verbose(&format!(
1313             "{}< {:?}",
1314             "  ".repeat(self.stack.borrow().len()),
1315             step
1316         ));
1317         self.cache.put(step, out.clone());
1318         out
1319     }
1320 }
1321
1322 #[cfg(test)]
1323 mod __test {
1324     use super::*;
1325     use crate::config::Config;
1326     use std::thread;
1327
1328     use pretty_assertions::assert_eq;
1329
1330     fn configure(host: &[&str], target: &[&str]) -> Config {
1331         let mut config = Config::default_opts();
1332         // don't save toolstates
1333         config.save_toolstates = None;
1334         config.run_host_only = true;
1335         config.dry_run = true;
1336         // try to avoid spurious failures in dist where we create/delete each others file
1337         let dir = config.out.join("tmp-rustbuild-tests").join(
1338             &thread::current()
1339                 .name()
1340                 .unwrap_or("unknown")
1341                 .replace(":", "-"),
1342         );
1343         t!(fs::create_dir_all(&dir));
1344         config.out = dir;
1345         config.build = INTERNER.intern_str("A");
1346         config.hosts = vec![config.build]
1347             .clone()
1348             .into_iter()
1349             .chain(host.iter().map(|s| INTERNER.intern_str(s)))
1350             .collect::<Vec<_>>();
1351         config.targets = config
1352             .hosts
1353             .clone()
1354             .into_iter()
1355             .chain(target.iter().map(|s| INTERNER.intern_str(s)))
1356             .collect::<Vec<_>>();
1357         config
1358     }
1359
1360     fn first<A, B>(v: Vec<(A, B)>) -> Vec<A> {
1361         v.into_iter().map(|(a, _)| a).collect::<Vec<_>>()
1362     }
1363
1364     #[test]
1365     fn dist_baseline() {
1366         let build = Build::new(configure(&[], &[]));
1367         let mut builder = Builder::new(&build);
1368         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1369
1370         let a = INTERNER.intern_str("A");
1371
1372         assert_eq!(
1373             first(builder.cache.all::<dist::Docs>()),
1374             &[dist::Docs { host: a },]
1375         );
1376         assert_eq!(
1377             first(builder.cache.all::<dist::Mingw>()),
1378             &[dist::Mingw { host: a },]
1379         );
1380         assert_eq!(
1381             first(builder.cache.all::<dist::Rustc>()),
1382             &[dist::Rustc {
1383                 compiler: Compiler { host: a, stage: 2 }
1384             },]
1385         );
1386         assert_eq!(
1387             first(builder.cache.all::<dist::Std>()),
1388             &[dist::Std {
1389                 compiler: Compiler { host: a, stage: 1 },
1390                 target: a,
1391             },]
1392         );
1393         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1394     }
1395
1396     #[test]
1397     fn dist_with_targets() {
1398         let build = Build::new(configure(&[], &["B"]));
1399         let mut builder = Builder::new(&build);
1400         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1401
1402         let a = INTERNER.intern_str("A");
1403         let b = INTERNER.intern_str("B");
1404
1405         assert_eq!(
1406             first(builder.cache.all::<dist::Docs>()),
1407             &[
1408                 dist::Docs { host: a },
1409                 dist::Docs { host: b },
1410             ]
1411         );
1412         assert_eq!(
1413             first(builder.cache.all::<dist::Mingw>()),
1414             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1415         );
1416         assert_eq!(
1417             first(builder.cache.all::<dist::Rustc>()),
1418             &[dist::Rustc {
1419                 compiler: Compiler { host: a, stage: 2 }
1420             },]
1421         );
1422         assert_eq!(
1423             first(builder.cache.all::<dist::Std>()),
1424             &[
1425                 dist::Std {
1426                     compiler: Compiler { host: a, stage: 1 },
1427                     target: a,
1428                 },
1429                 dist::Std {
1430                     compiler: Compiler { host: a, stage: 2 },
1431                     target: b,
1432                 },
1433             ]
1434         );
1435         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1436     }
1437
1438     #[test]
1439     fn dist_with_hosts() {
1440         let build = Build::new(configure(&["B"], &[]));
1441         let mut builder = Builder::new(&build);
1442         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1443
1444         let a = INTERNER.intern_str("A");
1445         let b = INTERNER.intern_str("B");
1446
1447         assert_eq!(
1448             first(builder.cache.all::<dist::Docs>()),
1449             &[
1450                 dist::Docs { host: a },
1451                 dist::Docs { host: b },
1452             ]
1453         );
1454         assert_eq!(
1455             first(builder.cache.all::<dist::Mingw>()),
1456             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1457         );
1458         assert_eq!(
1459             first(builder.cache.all::<dist::Rustc>()),
1460             &[
1461                 dist::Rustc {
1462                     compiler: Compiler { host: a, stage: 2 }
1463                 },
1464                 dist::Rustc {
1465                     compiler: Compiler { host: b, stage: 2 }
1466                 },
1467             ]
1468         );
1469         assert_eq!(
1470             first(builder.cache.all::<dist::Std>()),
1471             &[
1472                 dist::Std {
1473                     compiler: Compiler { host: a, stage: 1 },
1474                     target: a,
1475                 },
1476                 dist::Std {
1477                     compiler: Compiler { host: a, stage: 1 },
1478                     target: b,
1479                 },
1480             ]
1481         );
1482         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1483     }
1484
1485     #[test]
1486     fn dist_only_cross_host() {
1487         let a = INTERNER.intern_str("A");
1488         let b = INTERNER.intern_str("B");
1489         let mut build = Build::new(configure(&["B"], &[]));
1490         build.config.docs = false;
1491         build.config.extended = true;
1492         build.hosts = vec![b];
1493         let mut builder = Builder::new(&build);
1494         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1495
1496         assert_eq!(
1497             first(builder.cache.all::<dist::Rustc>()),
1498             &[
1499                 dist::Rustc {
1500                     compiler: Compiler { host: b, stage: 2 }
1501                 },
1502             ]
1503         );
1504         assert_eq!(
1505             first(builder.cache.all::<compile::Rustc>()),
1506             &[
1507                 compile::Rustc {
1508                     compiler: Compiler { host: a, stage: 0 },
1509                     target: a,
1510                 },
1511                 compile::Rustc {
1512                     compiler: Compiler { host: a, stage: 1 },
1513                     target: b,
1514                 },
1515             ]
1516         );
1517     }
1518
1519     #[test]
1520     fn dist_with_targets_and_hosts() {
1521         let build = Build::new(configure(&["B"], &["C"]));
1522         let mut builder = Builder::new(&build);
1523         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1524
1525         let a = INTERNER.intern_str("A");
1526         let b = INTERNER.intern_str("B");
1527         let c = INTERNER.intern_str("C");
1528
1529         assert_eq!(
1530             first(builder.cache.all::<dist::Docs>()),
1531             &[
1532                 dist::Docs { host: a },
1533                 dist::Docs { host: b },
1534                 dist::Docs { host: c },
1535             ]
1536         );
1537         assert_eq!(
1538             first(builder.cache.all::<dist::Mingw>()),
1539             &[
1540                 dist::Mingw { host: a },
1541                 dist::Mingw { host: b },
1542                 dist::Mingw { host: c },
1543             ]
1544         );
1545         assert_eq!(
1546             first(builder.cache.all::<dist::Rustc>()),
1547             &[
1548                 dist::Rustc {
1549                     compiler: Compiler { host: a, stage: 2 }
1550                 },
1551                 dist::Rustc {
1552                     compiler: Compiler { host: b, stage: 2 }
1553                 },
1554             ]
1555         );
1556         assert_eq!(
1557             first(builder.cache.all::<dist::Std>()),
1558             &[
1559                 dist::Std {
1560                     compiler: Compiler { host: a, stage: 1 },
1561                     target: a,
1562                 },
1563                 dist::Std {
1564                     compiler: Compiler { host: a, stage: 1 },
1565                     target: b,
1566                 },
1567                 dist::Std {
1568                     compiler: Compiler { host: a, stage: 2 },
1569                     target: c,
1570                 },
1571             ]
1572         );
1573         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1574     }
1575
1576     #[test]
1577     fn dist_with_target_flag() {
1578         let mut config = configure(&["B"], &["C"]);
1579         config.run_host_only = false; // as-if --target=C was passed
1580         let build = Build::new(config);
1581         let mut builder = Builder::new(&build);
1582         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1583
1584         let a = INTERNER.intern_str("A");
1585         let b = INTERNER.intern_str("B");
1586         let c = INTERNER.intern_str("C");
1587
1588         assert_eq!(
1589             first(builder.cache.all::<dist::Docs>()),
1590             &[
1591                 dist::Docs { host: a },
1592                 dist::Docs { host: b },
1593                 dist::Docs { host: c },
1594             ]
1595         );
1596         assert_eq!(
1597             first(builder.cache.all::<dist::Mingw>()),
1598             &[
1599                 dist::Mingw { host: a },
1600                 dist::Mingw { host: b },
1601                 dist::Mingw { host: c },
1602             ]
1603         );
1604         assert_eq!(first(builder.cache.all::<dist::Rustc>()), &[]);
1605         assert_eq!(
1606             first(builder.cache.all::<dist::Std>()),
1607             &[
1608                 dist::Std {
1609                     compiler: Compiler { host: a, stage: 1 },
1610                     target: a,
1611                 },
1612                 dist::Std {
1613                     compiler: Compiler { host: a, stage: 1 },
1614                     target: b,
1615                 },
1616                 dist::Std {
1617                     compiler: Compiler { host: a, stage: 2 },
1618                     target: c,
1619                 },
1620             ]
1621         );
1622         assert_eq!(first(builder.cache.all::<dist::Src>()), &[]);
1623     }
1624
1625     #[test]
1626     fn dist_with_same_targets_and_hosts() {
1627         let build = Build::new(configure(&["B"], &["B"]));
1628         let mut builder = Builder::new(&build);
1629         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Dist), &[]);
1630
1631         let a = INTERNER.intern_str("A");
1632         let b = INTERNER.intern_str("B");
1633
1634         assert_eq!(
1635             first(builder.cache.all::<dist::Docs>()),
1636             &[
1637                 dist::Docs { host: a },
1638                 dist::Docs { host: b },
1639             ]
1640         );
1641         assert_eq!(
1642             first(builder.cache.all::<dist::Mingw>()),
1643             &[dist::Mingw { host: a }, dist::Mingw { host: b },]
1644         );
1645         assert_eq!(
1646             first(builder.cache.all::<dist::Rustc>()),
1647             &[
1648                 dist::Rustc {
1649                     compiler: Compiler { host: a, stage: 2 }
1650                 },
1651                 dist::Rustc {
1652                     compiler: Compiler { host: b, stage: 2 }
1653                 },
1654             ]
1655         );
1656         assert_eq!(
1657             first(builder.cache.all::<dist::Std>()),
1658             &[
1659                 dist::Std {
1660                     compiler: Compiler { host: a, stage: 1 },
1661                     target: a,
1662                 },
1663                 dist::Std {
1664                     compiler: Compiler { host: a, stage: 1 },
1665                     target: b,
1666                 },
1667             ]
1668         );
1669         assert_eq!(first(builder.cache.all::<dist::Src>()), &[dist::Src]);
1670         assert_eq!(
1671             first(builder.cache.all::<compile::Std>()),
1672             &[
1673                 compile::Std {
1674                     compiler: Compiler { host: a, stage: 0 },
1675                     target: a,
1676                 },
1677                 compile::Std {
1678                     compiler: Compiler { host: a, stage: 1 },
1679                     target: a,
1680                 },
1681                 compile::Std {
1682                     compiler: Compiler { host: a, stage: 2 },
1683                     target: a,
1684                 },
1685                 compile::Std {
1686                     compiler: Compiler { host: a, stage: 1 },
1687                     target: b,
1688                 },
1689                 compile::Std {
1690                     compiler: Compiler { host: a, stage: 2 },
1691                     target: b,
1692                 },
1693             ]
1694         );
1695         assert_eq!(
1696             first(builder.cache.all::<compile::Test>()),
1697             &[
1698                 compile::Test {
1699                     compiler: Compiler { host: a, stage: 0 },
1700                     target: a,
1701                 },
1702                 compile::Test {
1703                     compiler: Compiler { host: a, stage: 1 },
1704                     target: a,
1705                 },
1706                 compile::Test {
1707                     compiler: Compiler { host: a, stage: 2 },
1708                     target: a,
1709                 },
1710                 compile::Test {
1711                     compiler: Compiler { host: a, stage: 1 },
1712                     target: b,
1713                 },
1714             ]
1715         );
1716         assert_eq!(
1717             first(builder.cache.all::<compile::Assemble>()),
1718             &[
1719                 compile::Assemble {
1720                     target_compiler: Compiler { host: a, stage: 0 },
1721                 },
1722                 compile::Assemble {
1723                     target_compiler: Compiler { host: a, stage: 1 },
1724                 },
1725                 compile::Assemble {
1726                     target_compiler: Compiler { host: a, stage: 2 },
1727                 },
1728                 compile::Assemble {
1729                     target_compiler: Compiler { host: b, stage: 2 },
1730                 },
1731             ]
1732         );
1733     }
1734
1735     #[test]
1736     fn build_default() {
1737         let build = Build::new(configure(&["B"], &["C"]));
1738         let mut builder = Builder::new(&build);
1739         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1740
1741         let a = INTERNER.intern_str("A");
1742         let b = INTERNER.intern_str("B");
1743         let c = INTERNER.intern_str("C");
1744
1745         assert!(!builder.cache.all::<compile::Std>().is_empty());
1746         assert!(!builder.cache.all::<compile::Assemble>().is_empty());
1747         assert_eq!(
1748             first(builder.cache.all::<compile::Rustc>()),
1749             &[
1750                 compile::Rustc {
1751                     compiler: Compiler { host: a, stage: 0 },
1752                     target: a,
1753                 },
1754                 compile::Rustc {
1755                     compiler: Compiler { host: a, stage: 1 },
1756                     target: a,
1757                 },
1758                 compile::Rustc {
1759                     compiler: Compiler { host: a, stage: 2 },
1760                     target: a,
1761                 },
1762                 compile::Rustc {
1763                     compiler: Compiler { host: b, stage: 2 },
1764                     target: a,
1765                 },
1766                 compile::Rustc {
1767                     compiler: Compiler { host: a, stage: 1 },
1768                     target: b,
1769                 },
1770                 compile::Rustc {
1771                     compiler: Compiler { host: a, stage: 2 },
1772                     target: b,
1773                 },
1774                 compile::Rustc {
1775                     compiler: Compiler { host: b, stage: 2 },
1776                     target: b,
1777                 },
1778             ]
1779         );
1780
1781         assert_eq!(
1782             first(builder.cache.all::<compile::Test>()),
1783             &[
1784                 compile::Test {
1785                     compiler: Compiler { host: a, stage: 0 },
1786                     target: a,
1787                 },
1788                 compile::Test {
1789                     compiler: Compiler { host: a, stage: 1 },
1790                     target: a,
1791                 },
1792                 compile::Test {
1793                     compiler: Compiler { host: a, stage: 2 },
1794                     target: a,
1795                 },
1796                 compile::Test {
1797                     compiler: Compiler { host: b, stage: 2 },
1798                     target: a,
1799                 },
1800                 compile::Test {
1801                     compiler: Compiler { host: a, stage: 1 },
1802                     target: b,
1803                 },
1804                 compile::Test {
1805                     compiler: Compiler { host: a, stage: 2 },
1806                     target: b,
1807                 },
1808                 compile::Test {
1809                     compiler: Compiler { host: b, stage: 2 },
1810                     target: b,
1811                 },
1812                 compile::Test {
1813                     compiler: Compiler { host: a, stage: 2 },
1814                     target: c,
1815                 },
1816                 compile::Test {
1817                     compiler: Compiler { host: b, stage: 2 },
1818                     target: c,
1819                 },
1820             ]
1821         );
1822     }
1823
1824     #[test]
1825     fn build_with_target_flag() {
1826         let mut config = configure(&["B"], &["C"]);
1827         config.run_host_only = false;
1828         let build = Build::new(config);
1829         let mut builder = Builder::new(&build);
1830         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[]);
1831
1832         let a = INTERNER.intern_str("A");
1833         let b = INTERNER.intern_str("B");
1834         let c = INTERNER.intern_str("C");
1835
1836         assert!(!builder.cache.all::<compile::Std>().is_empty());
1837         assert_eq!(
1838             first(builder.cache.all::<compile::Assemble>()),
1839             &[
1840                 compile::Assemble {
1841                     target_compiler: Compiler { host: a, stage: 0 },
1842                 },
1843                 compile::Assemble {
1844                     target_compiler: Compiler { host: a, stage: 1 },
1845                 },
1846                 compile::Assemble {
1847                     target_compiler: Compiler { host: a, stage: 2 },
1848                 },
1849                 compile::Assemble {
1850                     target_compiler: Compiler { host: b, stage: 2 },
1851                 },
1852             ]
1853         );
1854         assert_eq!(
1855             first(builder.cache.all::<compile::Rustc>()),
1856             &[
1857                 compile::Rustc {
1858                     compiler: Compiler { host: a, stage: 0 },
1859                     target: a,
1860                 },
1861                 compile::Rustc {
1862                     compiler: Compiler { host: a, stage: 1 },
1863                     target: a,
1864                 },
1865                 compile::Rustc {
1866                     compiler: Compiler { host: a, stage: 1 },
1867                     target: b,
1868                 },
1869             ]
1870         );
1871
1872         assert_eq!(
1873             first(builder.cache.all::<compile::Test>()),
1874             &[
1875                 compile::Test {
1876                     compiler: Compiler { host: a, stage: 0 },
1877                     target: a,
1878                 },
1879                 compile::Test {
1880                     compiler: Compiler { host: a, stage: 1 },
1881                     target: a,
1882                 },
1883                 compile::Test {
1884                     compiler: Compiler { host: a, stage: 2 },
1885                     target: a,
1886                 },
1887                 compile::Test {
1888                     compiler: Compiler { host: b, stage: 2 },
1889                     target: a,
1890                 },
1891                 compile::Test {
1892                     compiler: Compiler { host: a, stage: 1 },
1893                     target: b,
1894                 },
1895                 compile::Test {
1896                     compiler: Compiler { host: a, stage: 2 },
1897                     target: b,
1898                 },
1899                 compile::Test {
1900                     compiler: Compiler { host: b, stage: 2 },
1901                     target: b,
1902                 },
1903                 compile::Test {
1904                     compiler: Compiler { host: a, stage: 2 },
1905                     target: c,
1906                 },
1907                 compile::Test {
1908                     compiler: Compiler { host: b, stage: 2 },
1909                     target: c,
1910                 },
1911             ]
1912         );
1913     }
1914
1915     #[test]
1916     fn test_with_no_doc_stage0() {
1917         let mut config = configure(&[], &[]);
1918         config.stage = Some(0);
1919         config.cmd = Subcommand::Test {
1920             paths: vec!["src/libstd".into()],
1921             test_args: vec![],
1922             rustc_args: vec![],
1923             fail_fast: true,
1924             doc_tests: DocTests::No,
1925             bless: false,
1926             compare_mode: None,
1927             rustfix_coverage: false,
1928         };
1929
1930         let build = Build::new(config);
1931         let mut builder = Builder::new(&build);
1932
1933         let host = INTERNER.intern_str("A");
1934
1935         builder.run_step_descriptions(
1936             &[StepDescription::from::<test::Crate>()],
1937             &["src/libstd".into()],
1938         );
1939
1940         // Ensure we don't build any compiler artifacts.
1941         assert!(!builder.cache.contains::<compile::Rustc>());
1942         assert_eq!(
1943             first(builder.cache.all::<test::Crate>()),
1944             &[test::Crate {
1945                 compiler: Compiler { host, stage: 0 },
1946                 target: host,
1947                 mode: Mode::Std,
1948                 test_kind: test::TestKind::Test,
1949                 krate: INTERNER.intern_str("std"),
1950             },]
1951         );
1952     }
1953
1954     #[test]
1955     fn test_exclude() {
1956         let mut config = configure(&[], &[]);
1957         config.exclude = vec![
1958             "src/test/run-pass".into(),
1959             "src/tools/tidy".into(),
1960         ];
1961         config.cmd = Subcommand::Test {
1962             paths: Vec::new(),
1963             test_args: Vec::new(),
1964             rustc_args: Vec::new(),
1965             fail_fast: true,
1966             doc_tests: DocTests::No,
1967             bless: false,
1968             compare_mode: None,
1969             rustfix_coverage: false,
1970         };
1971
1972         let build = Build::new(config);
1973         let builder = Builder::new(&build);
1974         builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Test), &[]);
1975
1976         // Ensure we have really excluded run-pass & tidy
1977         assert!(!builder.cache.contains::<test::RunPass>());
1978         assert!(!builder.cache.contains::<test::Tidy>());
1979
1980         // Ensure other tests are not affected.
1981         assert!(builder.cache.contains::<test::RunPassFullDeps>());
1982         assert!(builder.cache.contains::<test::RustdocUi>());
1983     }
1984 }