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