]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Fix panic when `x.py` is called without any arguments.
[rust.git] / src / bootstrap / builder.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::any::Any;
12 use std::cell::RefCell;
13 use std::collections::BTreeSet;
14 use std::env;
15 use std::fmt::Debug;
16 use std::fs;
17 use std::hash::Hash;
18 use std::ops::Deref;
19 use std::path::{Path, PathBuf};
20 use std::process::Command;
21
22 use compile;
23 use install;
24 use dist;
25 use util::{exe, libdir, add_lib_path};
26 use {Build, Mode};
27 use cache::{INTERNER, Interned, Cache};
28 use check;
29 use test;
30 use flags::Subcommand;
31 use doc;
32 use tool;
33 use native;
34
35 pub use Compiler;
36
37 pub struct Builder<'a> {
38     pub build: &'a Build,
39     pub top_stage: u32,
40     pub kind: Kind,
41     cache: Cache,
42     stack: RefCell<Vec<Box<Any>>>,
43 }
44
45 impl<'a> Deref for Builder<'a> {
46     type Target = Build;
47
48     fn deref(&self) -> &Self::Target {
49         self.build
50     }
51 }
52
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.
56     type Output: Clone;
57
58     const DEFAULT: bool = false;
59
60     /// Run this rule for all hosts without cross compiling.
61     const ONLY_HOSTS: bool = false;
62
63     /// Run this rule for all targets, but only with the native host.
64     const ONLY_BUILD_TARGETS: bool = false;
65
66     /// Only run this step with the build triple as host and target.
67     const ONLY_BUILD: bool = false;
68
69     /// Primary function to execute this rule. Can call `builder.ensure(...)`
70     /// with other steps to run those.
71     fn run(self, builder: &Builder) -> Self::Output;
72
73     /// When bootstrap is passed a set of paths, this controls whether this rule
74     /// will execute. However, it does not get called in a "default" context
75     /// when we are not passed any paths; in that case, make_run is called
76     /// directly.
77     fn should_run(run: ShouldRun) -> ShouldRun;
78
79     /// Build up a "root" rule, either as a default rule or from a path passed
80     /// to us.
81     ///
82     /// When path is `None`, we are executing in a context where no paths were
83     /// passed. When `./x.py build` is run, for example, this rule could get
84     /// called if it is in the correct list below with a path of `None`.
85     fn make_run(_run: RunConfig) {
86         // It is reasonable to not have an implementation of make_run for rules
87         // who do not want to get called from the root context. This means that
88         // they are likely dependencies (e.g., sysroot creation) or similar, and
89         // as such calling them from ./x.py isn't logical.
90         unimplemented!()
91     }
92 }
93
94 pub struct RunConfig<'a> {
95     pub builder: &'a Builder<'a>,
96     pub host: Interned<String>,
97     pub target: Interned<String>,
98     pub path: PathBuf,
99 }
100
101 struct StepDescription {
102     default: bool,
103     only_hosts: bool,
104     only_build_targets: bool,
105     only_build: bool,
106     should_run: fn(ShouldRun) -> ShouldRun,
107     make_run: fn(RunConfig),
108     name: &'static str,
109 }
110
111 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
112 struct PathSet {
113     set: BTreeSet<PathBuf>,
114 }
115
116 impl PathSet {
117     fn empty() -> PathSet {
118         PathSet { set: BTreeSet::new() }
119     }
120
121     fn one<P: Into<PathBuf>>(path: P) -> PathSet {
122         let mut set = BTreeSet::new();
123         set.insert(path.into());
124         PathSet { set }
125     }
126
127     fn has(&self, needle: &Path) -> bool {
128         self.set.iter().any(|p| p.ends_with(needle))
129     }
130
131     fn path(&self, builder: &Builder) -> PathBuf {
132         self.set.iter().next().unwrap_or(&builder.build.src).to_path_buf()
133     }
134 }
135
136 impl StepDescription {
137     fn from<S: Step>() -> StepDescription {
138         StepDescription {
139             default: S::DEFAULT,
140             only_hosts: S::ONLY_HOSTS,
141             only_build_targets: S::ONLY_BUILD_TARGETS,
142             only_build: S::ONLY_BUILD,
143             should_run: S::should_run,
144             make_run: S::make_run,
145             name: unsafe { ::std::intrinsics::type_name::<S>() },
146         }
147     }
148
149     fn maybe_run(&self, builder: &Builder, pathset: &PathSet) {
150         if builder.config.exclude.iter().any(|e| pathset.has(e)) {
151             eprintln!("Skipping {:?} because it is excluded", pathset);
152             return;
153         } else if !builder.config.exclude.is_empty() {
154             eprintln!("{:?} not skipped for {:?} -- not in {:?}", pathset,
155                 self.name, builder.config.exclude);
156         }
157         let build = builder.build;
158         let hosts = if self.only_build_targets || self.only_build {
159             build.build_triple()
160         } else {
161             &build.hosts
162         };
163
164         // Determine the targets participating in this rule.
165         let targets = if self.only_hosts {
166             if build.config.run_host_only {
167                 &[]
168             } else if self.only_build {
169                 build.build_triple()
170             } else {
171                 &build.hosts
172             }
173         } else {
174             &build.targets
175         };
176
177         for host in hosts {
178             for target in targets {
179                 let run = RunConfig {
180                     builder,
181                     path: pathset.path(builder),
182                     host: *host,
183                     target: *target,
184                 };
185                 (self.make_run)(run);
186             }
187         }
188     }
189
190     fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
191         let should_runs = v.iter().map(|desc| {
192             (desc.should_run)(ShouldRun::new(builder))
193         }).collect::<Vec<_>>();
194
195         // sanity checks on rules
196         for (desc, should_run) in v.iter().zip(&should_runs) {
197             assert!(!should_run.paths.is_empty(),
198                 "{:?} should have at least one pathset", desc.name);
199         }
200
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);
206                     }
207                 }
208             }
209         } else {
210             for path in paths {
211                 let mut attempted_run = false;
212                 for (desc, should_run) in v.iter().zip(&should_runs) {
213                     if let Some(pathset) = should_run.pathset_for_path(path) {
214                         attempted_run = true;
215                         desc.maybe_run(builder, pathset);
216                     }
217                 }
218
219                 if !attempted_run {
220                     panic!("Error: no rules matched {}.", path.display());
221                 }
222             }
223         }
224     }
225 }
226
227 #[derive(Clone)]
228 pub struct ShouldRun<'a> {
229     pub builder: &'a Builder<'a>,
230     // use a BTreeSet to maintain sort order
231     paths: BTreeSet<PathSet>,
232
233     // If this is a default rule, this is an additional constraint placed on
234     // it's run. Generally something like compiler docs being enabled.
235     is_really_default: bool,
236 }
237
238 impl<'a> ShouldRun<'a> {
239     fn new(builder: &'a Builder) -> ShouldRun<'a> {
240         ShouldRun {
241             builder,
242             paths: BTreeSet::new(),
243             is_really_default: true, // by default no additional conditions
244         }
245     }
246
247     pub fn default_condition(mut self, cond: bool) -> Self {
248         self.is_really_default = cond;
249         self
250     }
251
252     // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
253     // ever be used, but as we transition to having all rules properly handle passing krate(...) by
254     // actually doing something different for every crate passed.
255     pub fn all_krates(mut self, name: &str) -> Self {
256         let mut set = BTreeSet::new();
257         for krate in self.builder.in_tree_crates(name) {
258             set.insert(PathBuf::from(&krate.path));
259         }
260         self.paths.insert(PathSet { set });
261         self
262     }
263
264     pub fn krate(mut self, name: &str) -> Self {
265         for krate in self.builder.in_tree_crates(name) {
266             self.paths.insert(PathSet::one(&krate.path));
267         }
268         self
269     }
270
271     // single, non-aliased path
272     pub fn path(self, path: &str) -> Self {
273         self.paths(&[path])
274     }
275
276     // multiple aliases for the same job
277     pub fn paths(mut self, paths: &[&str]) -> Self {
278         self.paths.insert(PathSet {
279             set: paths.iter().map(PathBuf::from).collect(),
280         });
281         self
282     }
283
284     // allows being more explicit about why should_run in Step returns the value passed to it
285     pub fn never(mut self) -> ShouldRun<'a> {
286         self.paths.insert(PathSet::empty());
287         self
288     }
289
290     fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
291         self.paths.iter().find(|pathset| pathset.has(path))
292     }
293 }
294
295 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
296 pub enum Kind {
297     Build,
298     Check,
299     Test,
300     Bench,
301     Dist,
302     Doc,
303     Install,
304 }
305
306 impl<'a> Builder<'a> {
307     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
308         macro_rules! describe {
309             ($($rule:ty),+ $(,)*) => {{
310                 vec![$(StepDescription::from::<$rule>()),+]
311             }};
312         }
313         match kind {
314             Kind::Build => describe!(compile::Std, compile::Test, compile::Rustc,
315                 compile::StartupObjects, tool::BuildManifest, tool::Rustbook, tool::ErrorIndex,
316                 tool::UnstableBookGen, tool::Tidy, tool::Linkchecker, tool::CargoTest,
317                 tool::Compiletest, tool::RemoteTestServer, tool::RemoteTestClient,
318                 tool::RustInstaller, tool::Cargo, tool::Rls, tool::Rustdoc, tool::Clippy,
319                 native::Llvm, tool::Rustfmt, tool::Miri),
320             Kind::Check => describe!(check::Std, check::Test, check::Rustc),
321             Kind::Test => describe!(test::Tidy, test::Bootstrap, test::Ui, test::RunPass,
322                 test::CompileFail, test::ParseFail, test::RunFail, test::RunPassValgrind,
323                 test::MirOpt, test::Codegen, test::CodegenUnits, test::Incremental, test::Debuginfo,
324                 test::UiFullDeps, test::RunPassFullDeps, test::RunFailFullDeps,
325                 test::CompileFailFullDeps, test::IncrementalFullDeps, test::Rustdoc, test::Pretty,
326                 test::RunPassPretty, test::RunFailPretty, test::RunPassValgrindPretty,
327                 test::RunPassFullDepsPretty, test::RunFailFullDepsPretty, test::RunMake,
328                 test::Crate, test::CrateLibrustc, test::Rustdoc, test::Linkcheck, test::Cargotest,
329                 test::Cargo, test::Rls, test::Docs, test::ErrorIndex, test::Distcheck,
330                 test::Rustfmt, test::Miri, test::Clippy, test::RustdocJS, test::RustdocTheme),
331             Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
332             Kind::Doc => describe!(doc::UnstableBook, doc::UnstableBookGen, doc::TheBook,
333                 doc::Standalone, doc::Std, doc::Test, doc::Rustc, doc::ErrorIndex, doc::Nomicon,
334                 doc::Reference, doc::Rustdoc, doc::RustByExample, doc::CargoBook),
335             Kind::Dist => describe!(dist::Docs, dist::Mingw, dist::Rustc, dist::DebuggerScripts,
336                 dist::Std, dist::Analysis, dist::Src, dist::PlainSourceTarball, dist::Cargo,
337                 dist::Rls, dist::Rustfmt, dist::Extended, dist::HashSign),
338             Kind::Install => describe!(install::Docs, install::Std, install::Cargo, install::Rls,
339                 install::Rustfmt, install::Analysis, install::Src, install::Rustc),
340         }
341     }
342
343     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
344         let kind = match subcommand {
345             "build" => Kind::Build,
346             "doc" => Kind::Doc,
347             "test" => Kind::Test,
348             "bench" => Kind::Bench,
349             "dist" => Kind::Dist,
350             "install" => Kind::Install,
351             _ => return None,
352         };
353
354         let builder = Builder {
355             build,
356             top_stage: build.config.stage.unwrap_or(2),
357             kind,
358             cache: Cache::new(),
359             stack: RefCell::new(Vec::new()),
360         };
361
362         let builder = &builder;
363         let mut should_run = ShouldRun::new(builder);
364         for desc in Builder::get_step_descriptions(builder.kind) {
365             should_run = (desc.should_run)(should_run);
366         }
367         let mut help = String::from("Available paths:\n");
368         for pathset in should_run.paths {
369             for path in pathset.set {
370                 help.push_str(format!("    ./x.py {} {}\n", subcommand, path.display()).as_str());
371             }
372         }
373         Some(help)
374     }
375
376     pub fn run(build: &Build) {
377         let (kind, paths) = match build.config.cmd {
378             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
379             Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
380             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
381             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
382             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
383             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
384             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
385             Subcommand::Clean { .. } => panic!(),
386         };
387
388         if let Some(path) = paths.get(0) {
389             if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") {
390                 return;
391             }
392         }
393
394         let builder = Builder {
395             build,
396             top_stage: build.config.stage.unwrap_or(2),
397             kind,
398             cache: Cache::new(),
399             stack: RefCell::new(Vec::new()),
400         };
401
402         if kind == Kind::Dist {
403             assert!(!build.config.test_miri, "Do not distribute with miri enabled.\n\
404                 The distributed libraries would include all MIR (increasing binary size).
405                 The distributed MIR would include validation statements.");
406         }
407
408         StepDescription::run(&Builder::get_step_descriptions(builder.kind), &builder, paths);
409     }
410
411     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
412         let paths = paths.unwrap_or(&[]);
413         StepDescription::run(&Builder::get_step_descriptions(Kind::Doc), self, paths);
414     }
415
416     /// Obtain a compiler at a given stage and for a given host. Explicitly does
417     /// not take `Compiler` since all `Compiler` instances are meant to be
418     /// obtained through this function, since it ensures that they are valid
419     /// (i.e., built and assembled).
420     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
421         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
422     }
423
424     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
425         self.ensure(compile::Sysroot { compiler })
426     }
427
428     /// Returns the libdir where the standard library and other artifacts are
429     /// found for a compiler's sysroot.
430     pub fn sysroot_libdir(
431         &self, compiler: Compiler, target: Interned<String>
432     ) -> Interned<PathBuf> {
433         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
434         struct Libdir {
435             compiler: Compiler,
436             target: Interned<String>,
437         }
438         impl Step for Libdir {
439             type Output = Interned<PathBuf>;
440
441             fn should_run(run: ShouldRun) -> ShouldRun {
442                 run.never()
443             }
444
445             fn run(self, builder: &Builder) -> Interned<PathBuf> {
446                 let compiler = self.compiler;
447                 let lib = if compiler.stage >= 1 && builder.build.config.libdir.is_some() {
448                     builder.build.config.libdir.clone().unwrap()
449                 } else {
450                     PathBuf::from("lib")
451                 };
452                 let sysroot = builder.sysroot(self.compiler).join(lib)
453                     .join("rustlib").join(self.target).join("lib");
454                 let _ = fs::remove_dir_all(&sysroot);
455                 t!(fs::create_dir_all(&sysroot));
456                 INTERNER.intern_path(sysroot)
457             }
458         }
459         self.ensure(Libdir { compiler, target })
460     }
461
462     pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
463         self.sysroot_libdir(compiler, compiler.host)
464             .with_file_name("codegen-backends")
465     }
466
467     /// Returns the compiler's libdir where it stores the dynamic libraries that
468     /// it itself links against.
469     ///
470     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
471     /// Windows.
472     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
473         if compiler.is_snapshot(self) {
474             self.build.rustc_snapshot_libdir()
475         } else {
476             self.sysroot(compiler).join(libdir(&compiler.host))
477         }
478     }
479
480     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
481     /// library lookup path.
482     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
483         // Windows doesn't need dylib path munging because the dlls for the
484         // compiler live next to the compiler and the system will find them
485         // automatically.
486         if cfg!(windows) {
487             return
488         }
489
490         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
491     }
492
493     /// Get a path to the compiler specified.
494     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
495         if compiler.is_snapshot(self) {
496             self.initial_rustc.clone()
497         } else {
498             self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
499         }
500     }
501
502     pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
503         self.ensure(tool::Rustdoc { host })
504     }
505
506     pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
507         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
508         let compiler = self.compiler(self.top_stage, host);
509         cmd.env("RUSTC_STAGE", compiler.stage.to_string())
510            .env("RUSTC_SYSROOT", self.sysroot(compiler))
511            .env("RUSTDOC_LIBDIR", self.sysroot_libdir(compiler, self.build.build))
512            .env("CFG_RELEASE_CHANNEL", &self.build.config.channel)
513            .env("RUSTDOC_REAL", self.rustdoc(host))
514            .env("RUSTDOC_CRATE_VERSION", self.build.rust_version())
515            .env("RUSTC_BOOTSTRAP", "1");
516         if let Some(linker) = self.build.linker(host) {
517             cmd.env("RUSTC_TARGET_LINKER", linker);
518         }
519         cmd
520     }
521
522     /// Prepares an invocation of `cargo` to be run.
523     ///
524     /// This will create a `Command` that represents a pending execution of
525     /// Cargo. This cargo will be configured to use `compiler` as the actual
526     /// rustc compiler, its output will be scoped by `mode`'s output directory,
527     /// it will pass the `--target` flag for the specified `target`, and will be
528     /// executing the Cargo command `cmd`.
529     pub fn cargo(&self,
530              compiler: Compiler,
531              mode: Mode,
532              target: Interned<String>,
533              cmd: &str) -> Command {
534         let mut cargo = Command::new(&self.initial_cargo);
535         let out_dir = self.stage_out(compiler, mode);
536         cargo.env("CARGO_TARGET_DIR", out_dir)
537              .arg(cmd)
538              .arg("--target")
539              .arg(target);
540
541         // If we were invoked from `make` then that's already got a jobserver
542         // set up for us so no need to tell Cargo about jobs all over again.
543         if env::var_os("MAKEFLAGS").is_none() && env::var_os("MFLAGS").is_none() {
544              cargo.arg("-j").arg(self.jobs().to_string());
545         }
546
547         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
548         // Force cargo to output binaries with disambiguating hashes in the name
549         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
550
551         let stage;
552         if compiler.stage == 0 && self.local_rebuild {
553             // Assume the local-rebuild rustc already has stage1 features.
554             stage = 1;
555         } else {
556             stage = compiler.stage;
557         }
558
559         let mut extra_args = env::var(&format!("RUSTFLAGS_STAGE_{}", stage)).unwrap_or_default();
560         if stage != 0 {
561             let s = env::var("RUSTFLAGS_STAGE_NOT_0").unwrap_or_default();
562             extra_args.push_str(" ");
563             extra_args.push_str(&s);
564         }
565
566         if !extra_args.is_empty() {
567             cargo.env("RUSTFLAGS",
568                 format!("{} {}", env::var("RUSTFLAGS").unwrap_or_default(), extra_args));
569         }
570
571         // Customize the compiler we're running. Specify the compiler to cargo
572         // as our shim and then pass it some various options used to configure
573         // how the actual compiler itself is called.
574         //
575         // These variables are primarily all read by
576         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
577         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
578              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
579              .env("RUSTC_REAL", self.rustc(compiler))
580              .env("RUSTC_STAGE", stage.to_string())
581              .env("RUSTC_DEBUG_ASSERTIONS",
582                   self.config.rust_debug_assertions.to_string())
583              .env("RUSTC_SYSROOT", self.sysroot(compiler))
584              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
585              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
586              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
587              .env("RUSTDOC_REAL", if cmd == "doc" || cmd == "test" {
588                  self.rustdoc(compiler.host)
589              } else {
590                  PathBuf::from("/path/to/nowhere/rustdoc/not/required")
591              })
592              .env("TEST_MIRI", self.config.test_miri.to_string())
593              .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir());
594
595         if let Some(host_linker) = self.build.linker(compiler.host) {
596             cargo.env("RUSTC_HOST_LINKER", host_linker);
597         }
598         if let Some(target_linker) = self.build.linker(target) {
599             cargo.env("RUSTC_TARGET_LINKER", target_linker);
600         }
601         if cmd != "build" && cmd != "check" {
602             cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(self.compiler(2, self.build.build)));
603         }
604
605         if mode != Mode::Tool {
606             // Tools don't get debuginfo right now, e.g. cargo and rls don't
607             // get compiled with debuginfo.
608             // Adding debuginfo increases their sizes by a factor of 3-4.
609             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string());
610             cargo.env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string());
611             cargo.env("RUSTC_FORCE_UNSTABLE", "1");
612
613             // Currently the compiler depends on crates from crates.io, and
614             // then other crates can depend on the compiler (e.g. proc-macro
615             // crates). Let's say, for example that rustc itself depends on the
616             // bitflags crate. If an external crate then depends on the
617             // bitflags crate as well, we need to make sure they don't
618             // conflict, even if they pick the same version of bitflags. We'll
619             // want to make sure that e.g. a plugin and rustc each get their
620             // own copy of bitflags.
621
622             // Cargo ensures that this works in general through the -C metadata
623             // flag. This flag will frob the symbols in the binary to make sure
624             // they're different, even though the source code is the exact
625             // same. To solve this problem for the compiler we extend Cargo's
626             // already-passed -C metadata flag with our own. Our rustc.rs
627             // wrapper around the actual rustc will detect -C metadata being
628             // passed and frob it with this extra string we're passing in.
629             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
630         }
631
632         if let Some(x) = self.crt_static(target) {
633             cargo.env("RUSTC_CRT_STATIC", x.to_string());
634         }
635
636         // Enable usage of unstable features
637         cargo.env("RUSTC_BOOTSTRAP", "1");
638         self.add_rust_test_threads(&mut cargo);
639
640         // Almost all of the crates that we compile as part of the bootstrap may
641         // have a build script, including the standard library. To compile a
642         // build script, however, it itself needs a standard library! This
643         // introduces a bit of a pickle when we're compiling the standard
644         // library itself.
645         //
646         // To work around this we actually end up using the snapshot compiler
647         // (stage0) for compiling build scripts of the standard library itself.
648         // The stage0 compiler is guaranteed to have a libstd available for use.
649         //
650         // For other crates, however, we know that we've already got a standard
651         // library up and running, so we can use the normal compiler to compile
652         // build scripts in that situation.
653         //
654         // If LLVM support is disabled we need to use the snapshot compiler to compile
655         // build scripts, as the new compiler doesn't support executables.
656         if mode == Mode::Libstd || !self.build.config.llvm_enabled {
657             cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
658                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
659         } else {
660             cargo.env("RUSTC_SNAPSHOT", self.rustc(compiler))
661                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
662         }
663
664         // Ignore incremental modes except for stage0, since we're
665         // not guaranteeing correctness across builds if the compiler
666         // is changing under your feet.`
667         if self.config.incremental && compiler.stage == 0 {
668             cargo.env("CARGO_INCREMENTAL", "1");
669         }
670
671         if let Some(ref on_fail) = self.config.on_fail {
672             cargo.env("RUSTC_ON_FAIL", on_fail);
673         }
674
675         cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
676
677         // Throughout the build Cargo can execute a number of build scripts
678         // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
679         // obtained previously to those build scripts.
680         // Build scripts use either the `cc` crate or `configure/make` so we pass
681         // the options through environment variables that are fetched and understood by both.
682         //
683         // FIXME: the guard against msvc shouldn't need to be here
684         if !target.contains("msvc") {
685             let cc = self.cc(target);
686             cargo.env(format!("CC_{}", target), cc)
687                  .env("CC", cc);
688
689             let cflags = self.cflags(target).join(" ");
690             cargo.env(format!("CFLAGS_{}", target), cflags.clone())
691                  .env("CFLAGS", cflags.clone());
692
693             if let Some(ar) = self.ar(target) {
694                 let ranlib = format!("{} s", ar.display());
695                 cargo.env(format!("AR_{}", target), ar)
696                      .env("AR", ar)
697                      .env(format!("RANLIB_{}", target), ranlib.clone())
698                      .env("RANLIB", ranlib);
699             }
700
701             if let Ok(cxx) = self.cxx(target) {
702                 cargo.env(format!("CXX_{}", target), cxx)
703                      .env("CXX", cxx)
704                      .env(format!("CXXFLAGS_{}", target), cflags.clone())
705                      .env("CXXFLAGS", cflags);
706             }
707         }
708
709         if mode == Mode::Libstd && self.config.extended && compiler.is_final_stage(self) {
710             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
711         }
712
713         // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
714         cargo.env("RUSTDOC_CRATE_VERSION", self.build.rust_version());
715
716         // Environment variables *required* throughout the build
717         //
718         // FIXME: should update code to not require this env var
719         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
720
721         // Set this for all builds to make sure doc builds also get it.
722         cargo.env("CFG_RELEASE_CHANNEL", &self.build.config.channel);
723
724         // This one's a bit tricky. As of the time of this writing the compiler
725         // links to the `winapi` crate on crates.io. This crate provides raw
726         // bindings to Windows system functions, sort of like libc does for
727         // Unix. This crate also, however, provides "import libraries" for the
728         // MinGW targets. There's an import library per dll in the windows
729         // distribution which is what's linked to. These custom import libraries
730         // are used because the winapi crate can reference Windows functions not
731         // present in the MinGW import libraries.
732         //
733         // For example MinGW may ship libdbghelp.a, but it may not have
734         // references to all the functions in the dbghelp dll. Instead the
735         // custom import library for dbghelp in the winapi crates has all this
736         // information.
737         //
738         // Unfortunately for us though the import libraries are linked by
739         // default via `-ldylib=winapi_foo`. That is, they're linked with the
740         // `dylib` type with a `winapi_` prefix (so the winapi ones don't
741         // conflict with the system MinGW ones). This consequently means that
742         // the binaries we ship of things like rustc_trans (aka the rustc_trans
743         // DLL) when linked against *again*, for example with procedural macros
744         // or plugins, will trigger the propagation logic of `-ldylib`, passing
745         // `-lwinapi_foo` to the linker again. This isn't actually available in
746         // our distribution, however, so the link fails.
747         //
748         // To solve this problem we tell winapi to not use its bundled import
749         // libraries. This means that it will link to the system MinGW import
750         // libraries by default, and the `-ldylib=foo` directives will still get
751         // passed to the final linker, but they'll look like `-lfoo` which can
752         // be resolved because MinGW has the import library. The downside is we
753         // don't get newer functions from Windows, but we don't use any of them
754         // anyway.
755         cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
756
757         if self.is_very_verbose() {
758             cargo.arg("-v");
759         }
760
761         // This must be kept before the thinlto check, as we set codegen units
762         // to 1 forcibly there.
763         if let Some(n) = self.config.rust_codegen_units {
764             cargo.env("RUSTC_CODEGEN_UNITS", n.to_string());
765         }
766
767         if self.config.rust_optimize {
768             // FIXME: cargo bench does not accept `--release`
769             if cmd != "bench" {
770                 cargo.arg("--release");
771             }
772
773             if self.config.rust_codegen_units.is_none() &&
774                self.build.is_rust_llvm(compiler.host) &&
775                self.config.rust_thinlto {
776                 cargo.env("RUSTC_THINLTO", "1");
777             } else if self.config.rust_codegen_units.is_none() {
778                 // Generally, if ThinLTO has been disabled for some reason, we
779                 // want to set the codegen units to 1. However, we shouldn't do
780                 // this if the option was specifically set by the user.
781                 cargo.env("RUSTC_CODEGEN_UNITS", "1");
782             }
783         }
784
785         if self.config.locked_deps {
786             cargo.arg("--locked");
787         }
788         if self.config.vendor || self.is_sudo {
789             cargo.arg("--frozen");
790         }
791
792         self.ci_env.force_coloring_in_ci(&mut cargo);
793
794         cargo
795     }
796
797     /// Ensure that a given step is built, returning it's output. This will
798     /// cache the step, so it is safe (and good!) to call this as often as
799     /// needed to ensure that all dependencies are built.
800     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
801         {
802             let mut stack = self.stack.borrow_mut();
803             for stack_step in stack.iter() {
804                 // should skip
805                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
806                     continue;
807                 }
808                 let mut out = String::new();
809                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
810                 for el in stack.iter().rev() {
811                     out += &format!("\t{:?}\n", el);
812                 }
813                 panic!(out);
814             }
815             if let Some(out) = self.cache.get(&step) {
816                 self.build.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
817
818                 return out;
819             }
820             self.build.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
821             stack.push(Box::new(step.clone()));
822         }
823         let out = step.clone().run(self);
824         {
825             let mut stack = self.stack.borrow_mut();
826             let cur_step = stack.pop().expect("step stack empty");
827             assert_eq!(cur_step.downcast_ref(), Some(&step));
828         }
829         self.build.verbose(&format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
830         self.cache.put(step, out.clone());
831         out
832     }
833 }